Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

EF Code first, how to register same table name with different schema?

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

I have also put the models in two different namespaces.

How i can register these tables in my DbContext class?

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!

like image 655
sam360 Avatar asked Dec 17 '11 18:12

sam360


People also ask

Can we have two schemas with the same name?

You can't. It's not possible to have two or more schemas with the same name in one database. But you can have objects with the same name in one database but in different schema .

Can we create table name with different schema?

This means it is not possible to have two different tables with the same name and different structures from different schemas (supporting multiple tables with the same name and same structure from different database instances is possible with the multi-source feature).

What is schema in EF core?

Schema. The default schema that EF Core uses to create database objects is dbo . You can change this behaviour using the ModelBuilder 's HasDefaultSchema method: protected override void OnModelCreating(ModelBuilder modelBuilder)


1 Answers

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.

like image 95
Ladislav Mrnka Avatar answered Oct 12 '22 19:10

Ladislav Mrnka