consider the following example:
A person can have multiple addresses. A store can have multiple addresses. Both have a 1:M to the address table.
Using EF6,Code First, how do I set up my entities and mappings (FluentApi) to support this? In my experience with EF 1:M, the child table (address) is unique to its parent table (Person or Store). I would have a Person Table and a PersonAddressTable with a 1:M relationship. I would also have a Store and StoreAddress tables with their own 1:M relationship. Unfortunately for me, the existing data model is written this way.
Its my understanding that I define a 1:M relationship by adding a nav property on the child entity that points back to the parent. The child entity must also have an ID field (FK) that points back to the parent, and this FK Property must be marked as required on the child entity.
so in my example, the Address Entity would have
public virtual Person Person {get;set;}
public int PersonId {get;set;
public Virtual Store Store {get;set;}
public int StoreId {get;set;
and the Address entity mapper would define:
this.Property(i=>i.PersonId).IsRequired();
this.Property(i=>i.StoreId).IsRequired();
this.HasRequired(p=>p.Person)
.WithMany(c=>c.Addresses)
.HasForeignKey(c=>PersonId);
this.HasRequired(p=>p.Store)
.WithMany(c=>c.Addresses)
.HasForeignKey(c=>c.StoreId);
But depending on their parent, the child navigation property (Person or Store) will be null. When referencing addresses for a Person, the Address.Store nav property will be null, and when referencing addresses for a store, the Address.person nav property will be null.
How can I correctly define these relationships?
Thanks.
