问题
I have a question about how to configure the one to many relationship with a join table using Code First fluent API. I have a Company, Contact Object both share a common Address Object like below
Class Address {
public int AddressId
.....
}
Class Company {
public int CompanyId
......
public virtual ICollection<Address> Address
}
Class Contact {
public int ContactID
.......
public virtual ICollection<Address> Address
}
My expected DB structure would be
Company Table
CompanyId PK NOT NULL
.....
Contact Table
ContactId PK NOT NULL
.....
Address Table
AddressId PK NOT NULL
.....
CompanyAddress Table
CompanyId NOT NULL
AddressId NOT NULL
ContactAddress Table
ContactId NOT NULL
AddressId NOT NULL
I was able to achieve this by using the below fluent API
modelBuilder.Entity<Company>()
.HasMany(c => c.Address)
.WithMany()
.Map(m =>
{
m => m.MapLeftKey("CompanyId")
.MapRightKey("AddressId")
.ToTable("CompanyAddress")});
modelBuilder.Entity<Contact>()
.HasMany(c => c.Address)
.WithMany()
.Map(m =>
{
m => m.MapLeftKey("ContactId")
.MapRightKey("AddressId")
.ToTable("ContactAddress")});
but EF start to treat Company and Address as Many to Many relationship and when I try to delete Company or Contacts it does not delete the corresponding Address record(since EF treats them as many to many), how can I define this type of relationship using EF with cascading delete option. I searched for more than 3 days and was suprised no one has talked or raised this type of scenarios, so wondering whether my approach is wrong or the answer is very trivial.
回答1:
You cannot have that with the many-to-many (it's what you're creating - and what you described).
When you delete company / contact - the 'join' table records get deleted.
You can simplify that and just do this in your config (remove all you have):
modelBuilder.Entity<Company>()
.HasMany(c => c.Address)
.WithOptional()
.WillCascadeOnDelete(true);
modelBuilder.Entity<Contact>()
.HasMany(c => c.Address)
.WithOptional()
.WillCascadeOnDelete(true);
来源:https://stackoverflow.com/questions/15824135/one-to-many-relationship-with-join-table-using-ef-code-first