c# - Entity Framework 4.1 InverseProperty Attribute and ForeignKey -


i create 2 references between employee , team entities foreign keys. defined 2 entities follow

public class employee {     public int employeeid { get; set; }     public string name { get; set; }      [foreignkey("firstteam")]     public int firstteamid { get; set; }      [inverseproperty("firstemployees")]     public virtual team firstteam { get; set; }      [foreignkey("secondteam")]     public int secondteamid { get; set; }      [inverseproperty("secondemployees")]     public virtual team secondteam { get; set; } }  public class team {     public int id { get; set; }     public string teamname { get; set; }      [inverseproperty("firstteam")]     public virtual icollection<employee> firstemployees { get; set; }      [inverseproperty("secondteam")]     public virtual icollection<employee> secondemployees { get; set; } } 

i thought correct theoretically, shows exception follow :

{"introducing foreign key constraint 'employee_secondteam' on table 'employees' may cause cycles or multiple cascade paths. specify on delete no action or on update no action, or modify other foreign key constraints.\r\ncould not create constraint. see previous errors."} 

can me?

thanks in advance kwon

it theoretically correct sql server (not entity framework) doesn't because model allows single employee member of both first , second team. if team deleted cause multiple delete paths same employee entity.

this cannot used cascade deletes used default in ef code first if define foreign key mandatory (not nullable).

if want avoid exception must use fluent mapping:

public context : dbcontext {     public dbset<employee> employees { get; set; }     public dbset<team> teams { get; set; }      protected override void onmodelcreating(dbmodelbuilder modelbuilder)     {         base.onmodelcreating(modelbuilder);          modelbuilder.entity<employee>()                     .hasrequired(e => e.secondteam)                     .withmany(t => t.secondemployees)                     .hasforeignkey(e => e.firstteamid)                     .willcascadeondelete(false);          ...     } } 

this result in scenario must delete members of secondteam manually before delete team.


Comments