EF Code首先,如何使用不同的模式注册相同的表名?

时间:2021-02-04 16:36:45

We are using Entity Framework, Code First and in our database we have several tables that have the same name but in different Schemas.

我们正在使用Entity Framework,Code First,在我们的数据库中,我们有几个具有相同名称但在不同Schema中的表。

I have also put the models in two different namespaces.

我还将模型放在两个不同的命名空间中。

How i can register these tables in my DbContext class?

我如何在DbContext类中注册这些表?

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
    modelBuilder.Entity<Data.Schema1.Contact>().ToTable("Contact", "schema1");
    modelBuilder.Entity<Data.Schema2.Contact>().ToTable("Contact", "schema2");
}

Thanks for your help in advance!

感谢您的帮助!

1 个解决方案

#1


15  

Your classes must have different name or you must use separate context for every schema.

您的类必须具有不同的名称,或者必须为每个模式使用单独的上下文。

The reason for this is EDM model used internally. Even if you are using code-first it still creates EDM model on behind and it must follow all its restrictions and the way how POCO classes are matched to entities defined in CSDL model. Entities from EDM are and POCO classes are matched by class name (without namespaces). Because of that each class name mapped in the same context must be unique and different namespace doesn't make it different class name.

原因是内部使用的EDM模型。即使您使用的是代码优先,它仍然会在后面创建EDM模型,它必须遵循其所有限制以及POCO类与CSDL模型中定义的实体的匹配方式。来自EDM的实体和POCO类由类名匹配(没有名称空间)。因为在同一个上下文中映射的每个类名必须是唯一的,并且不同的名称空间不会使它成为不同的类名。

#1


15  

Your classes must have different name or you must use separate context for every schema.

您的类必须具有不同的名称,或者必须为每个模式使用单独的上下文。

The reason for this is EDM model used internally. Even if you are using code-first it still creates EDM model on behind and it must follow all its restrictions and the way how POCO classes are matched to entities defined in CSDL model. Entities from EDM are and POCO classes are matched by class name (without namespaces). Because of that each class name mapped in the same context must be unique and different namespace doesn't make it different class name.

原因是内部使用的EDM模型。即使您使用的是代码优先,它仍然会在后面创建EDM模型,它必须遵循其所有限制以及POCO类与CSDL模型中定义的实体的匹配方式。来自EDM的实体和POCO类由类名匹配(没有名称空间)。因为在同一个上下文中映射的每个类名必须是唯一的,并且不同的名称空间不会使它成为不同的类名。