I have read through several threads on StackOverflow and have not been able to figure this out. I am hoping someone can offer some advice. I have some POCO classes that look like 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 I really need this one
virtual Person Contact {get; set;}
}
Each Person record will have zero to many PersonContact records. Each PersonContact record links one Person record to one other Person record and indicates the type of relationship between the two Person records with the PersonContactTypeCode.
I need to be able to map this so that a Person record can be navigated to his related PersonContact records. Something like 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 so many combinations of Data Annotations and Fluent API that I can hardly remember where I started. I seemed to have the best luck with this 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 I try to add more than one PersonContact to a Person, I get this error:
Multiplicity constraint violated. The role 'Person_PersonContacts_Source' of the
relationship '...Entities.Person_PersonContacts' has multiplicity
1 or 0..1.
I really appreciate any help, I am just completely stumped right now. By the way, I am open to changing these POCOs if necessary.