Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to map table splitting in EF Code First?

How can I map table splitting with EF Code First? Table splitting for EDMX is described for example here. It allows mapping two entities with 1:1 relation into same table. I know I can do the similar mapping with entity and complex type but the big difference is that complex type can't be lazy loaded (or not loaded at all) which is the main reason for table splitting.

like image 611
Ladislav Mrnka Avatar asked Mar 22 '11 11:03

Ladislav Mrnka


People also ask

What is table splitting in Entity Framework?

EF Core allows to map two or more entities to a single row. This is called table splitting or table sharing.


1 Answers

Here is how I just got EF 4.1 (RC) to do table splitting in Code First.

  1. Define your two entities. Make sure to include the key in both entities. Also, include navigation properties in each entity pointing to the other entity.
  2. In your OnModelCreating override . . . a. Map both entities to the same table. b. Create the relationship between the two tables.

        modelBuilder.Entity<EntityOne>().ToTable("MySingleTable");
        modelBuilder.Entity<EntityTwo>().ToTable("MySingleTable");
    
        modelBuilder.Entity<EntityOne>().HasRequired(p => p.NavToEntityTwo).WithRequiredDependent(c => c.NavToEntityOne);
    

This is working for me, but realize that given the newness of the RC I've only been able to look at limited and simple scenarios.

like image 143
David Martin Avatar answered Oct 13 '22 09:10

David Martin