c# - Entity Framework: Two foreign keys connected by one collection -
i know there related topic: two foreign keys same table, can't find there fix problem. pretty new ef.
i have following model classes (code-first):
public class member { [key] public int memberid { get; set; } public string name {get; set;} public string surname { get; set; } public virtual icollection<marriage> marriages { get; set; } } public class marriage { [key] public int marriageid { get; set; } public string marriageplace { get; set; } public datetime marriagedate { get; set; } [foreignkey("husband")] public int husbandid { get; set; } [foreignkey("wife")] public int wifeid { get; set; } public virtual member husband { get; set; } public virtual member wife { get; set; } }
my problem both husband , wife should connected same marriage collection in member class. did that:
modelbuilder.entity<marriage>() .hasrequired<member>(m => m.husband) .withmany(m => m.marriages) .hasforeignkey(m => m.husbandid) .willcascadeondelete(false);
and husband connected merriages collection. breaks when i'm trying add same thing wife property:
modelbuilder.entity<marriage>() .hasrequired<member>(m => m.wife) .withmany(m => m.marriages) .hasforeignkey(m => m.wifeid) .willcascadeondelete(false);
and getting error:
error 1 schema specified not valid. errors: relationship 'familytree.models.marriage_husband' not loaded because type 'familytree.models.member' not available. c:\users\sumiteru\documents\visual studio 2013\projects\familytree\familytree\app.xaml 9 21 familytree
that error occurs becouse ef didn't know navigation property must use. in onmodelbuliding
method setting member's
foreign key marriages
twice, ef confused navigation property should use when populating marriages
, throws exception.
there's topic on ef codeplex forum, user named 'moozzyk' explains ef behavior more (in comment): link.
as solution, should collection navigation property in member
class , map wife
's or husbend
's foreign key it. can find same solution on anwser: link.
Comments
Post a Comment