entity framework - One to Many Relationship with Join Table using EF Code First -
i have question how configure 1 many relationship join table using code first fluent api. have company, contact object both share common address object 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 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 able achieve using 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 treat company , address many many relationship , when try delete company or contacts not delete corresponding address record(since ef treats them many many), how can define type of relationship using ef cascading delete option. searched more 3 days , suprised no 1 has talked or raised type of scenarios, wondering whether approach wrong or answer trivial.
you cannot have many-to-many (it's you're creating - , described).
when delete company / contact - 'join' table records deleted.
you can simplify , in config (remove have):
modelbuilder.entity<company>() .hasmany(c => c.address) .withoptional() .willcascadeondelete(true); modelbuilder.entity<contact>() .hasmany(c => c.address) .withoptional() .willcascadeondelete(true);
Comments
Post a Comment