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.
Asked
Active
Viewed 5,834 times
1 Answers
10
Here is how I just got EF 4.1 (RC) to do table splitting in Code First.
- 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.
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.

David Martin
- 513
- 6
- 20
-
I already tried this and it didn't work. I will try it again and let you know. – Ladislav Mrnka Mar 23 '11 at 21:50
-
Can you explain in what way it is not working? One thing that comes to mind is that I am not having the database generate the primary key value. Instead I am setting the key value in code, and I found I must add the value in both the first entity and the second entity before calling SaveChanges. – David Martin Mar 23 '11 at 22:03
-
It works. I have no idea what I misconfigured when I tried it. I also got the answer on MSDN forum where autogenerated ID is used as well as navigation property only on principal entity: http://social.msdn.microsoft.com/Forums/en-US/adodotnetentityframework/thread/71da8ea5-7e34-4f7b-941b-ccb1a5a26ea7/ – Ladislav Mrnka Mar 23 '11 at 22:32