entity framework - Code first mapping for self-related xref table -
i have read through several threads on stackoverflow , have not been able figure out. hoping can offer advice. have poco classes this:
person { int personcode {get; set;} ... virtual list<personcontact> {get; set;} } personcontact { int personpersoncode {get; set;} int contactpersoncode {get; set;} int personcontacttypecode {get; set;} virtual personcontacttype {get; set;} virtual person person {get; set;} // not sure need 1 virtual person contact {get; set;} }
each person record have 0 many personcontact records. each personcontact record links 1 person record 1 other person record , indicates type of relationship between 2 person records personcontacttypecode.
i need able map person record can navigated related personcontact records. this:
var john = new person(...); var david = new person(...); john.personcontacts.add(new personcontact { contact = david, personcontacttype = ... // manager });
and then
john.personcontacts .where(c => c.personcontacttype.personcontacttypecode == "manager") .firstordefault();
would return
david
i have tried many combinations of data annotations , fluent api can hardly remember started. seemed have best luck combination:
modelbuilder.entity<person>() .hasmany(entity => entity.personcontacts) .withrequired(person => person.person) .hasforeignkey(xref => xref.personpersoncode) .willcascadeondelete(false); modelbuilder.entity<person>() .hasmany(entity => entity.personcontacts) .withrequired(xref => xref.contact) .hasforeignkey(entity => entity.contactpersoncode) .willcascadeondelete(false);
but, when try add more 1 personcontact person, error:
multiplicity constraint violated. role 'person_personcontacts_source' of relationship '...entities.person_personcontacts' has multiplicity 1 or 0..1.
i appreciate help, stumped right now. way, open changing these pocos if necessary.
i'd guess it's because using same navigation property link personcontact.person
, personcontact.contact
.
assuming this:
person { int personcode {get; set;} ... virtual icollection<personcontact> personcontacts {get; set;} }
try like:
modelbuilder.entity<personcontact>() .hasrequired(x => x.person) .withmany(x => x.personcontacts) .hasforeignkey(x => x.personpersoncode) .willcascadeondelete(false); modelbuilder.entity<personcontact>() .hasrequired(x => x.contact) .withmany() .hasforeignkey(x => x.contactpersoncode) .willcascadeondelete(false);
Comments
Post a Comment