I have a model that has the following setup:
A member can be member of multiple memberlists. A memberlist can have multiple members. I also defined that a memberlist can have a seperate set of optional members. Basically I have a double n-m relationship between member and memberlist. What's more, a memberlist is always owned by a member, the one person that created the memberlist that is.
Entity framework code-first is unable to map this relationship correctly eventhough I tell it how to map the relationships. I get the following error when I try to use the DbContext the first time
Schema specified is not valid. Errors:
(32,6) : error 0040: Type MemberList_Members is not defined in namespace NerdCooking.Models (Alias=Self).
(33,6) : error 0040: Type MemberList_OptionalMembers is not defined in namespace NerdCooking.Models (Alias=Self).
The first attempt to use the model in the scenario fails, because it's clear EF doesn't know how to map the n-m relationships. So I told the framework explicitly how to fix the situation.
// Map the relation between members of a memberlist and the memberlist
// to a Membership table
modelBuilder.Entity<MemberList>().HasMany(memberList => memberList.Members)
.WithMany(member => member.MemberLists)
.Map(mapping => mapping.MapLeftKey("MemberId")
.MapRightKey("MemberListId").ToTable("Membership"));
// Map the relation between optional members of a memberlist and the memberlist
// to a separate table
modelBuilder.Entity<MemberList>().HasMany(memberList => memberList.OptionalMembers)
.WithMany(member => member.MemberLists)
.Map(mapping => mapping.MapLeftKey("MemberId")
.MapRightKey("MemberListId").ToTable("OptionalMembership"));
// Map the relationship between the owner and the memberlist
modelBuilder.Entity<MemberList>().HasRequired(memberList => memberList.Owner)
.WithMany(member => member.MemberLists).WillCascadeOnDelete(true);
Is this scenario possible with Entity framework 4.1 code-first? And if so, what's the best way to fix the mapping issue I'm experiencing?
I can always change the model so that it features a Membership entity that links a member to a memberlist. It makes the whole thing a bit more explicit and I can then add a property to that entity to mark it as optional.
I think however that this is a scenario that should have worked, so I hope someone did this before and knows what the trick is to get it working correctly.
All your mappings contain .WithMany(member => member.MemberLists)
. That is incorrect. You need separate navigation property for each relation = you can use each navigation property only for one relation mapping.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With