ef code first - Entity Framework - 3 tables have relationships with each other -
i have 3 tables follows:
applicationuser:
public class applicationuser : identityuser { ..some basic properties.. // navigation properties public virtual icollection<post> posts { get; set; } public virtual icollection<album> albums { get; set; } }
post:
public class post { public long id { get; set; } public string content { get; set; } public int? albumid { get; set; } public string userid { get; set; } public virtual applicationuser user { get; set; } public virtual album album { get; set; } }
album:
public class album { public int id { get; set; } public string name { get; set; } public string userid { get; set; } public virtual applicationuser user { get; set; } public virtual icollection<post> posts { get; set; } }
and applicationdbcontext:
modelbuilder.entity<applicationuser>() .hasmany(a=>a.posts) .withrequired(a=>a.user) .hasforeignkey(a=>a.userid) .willcascadeondelete(false); modelbuilder.entity<post>() .haskey(p => p.id); modelbuilder.entity<album>() .haskey(a => a.id); modelbuilder.entity<applicationuser>() .hasmany(u=>u.albums) .withoptional() .hasforeignkey(a=>a.userid) .willcascadeondelete(); modelbuilder.entity<album>() .hasmany(a=>a.posts) .withrequired() .hasforeignkey(p=>p.albumid) .willcascadeondelete();
when run migration , update database, error:
the alter table statement conflicted foreign key constraint "fk_dbo.posts_dbo.albums_albumid". conflict occurred in database "aspnet-link-20161012104217", table "dbo.albums", column 'id'.
could tell why conflict? seems pretty legit me.
in code set albumid
nullable
in configuration defined withrequeired()
:
public class post { public long id { get; set; } public string content { get; set; } public int? albumid { get; set; } //<-- 1 public string userid { get; set; } public virtual applicationuser user { get; set; } public virtual album album { get; set; } } modelbuilder.entity<album>() .hasmany(a=>a.posts) .withrequired() //<-- 1 .hasforeignkey(p=>p.albumid) .willcascadeondelete();
if albumid
nullable
should change configuration:
//ef default conventions set albumid foreign key modelbuilder.entity<album>() .hasmany(a=>a.posts) .withoptional(a=>a.album);
and if albumid
isn't nullable
change property:
public class post { public long id { get; set; } public string content { get; set; } public int albumid { get; set; } public string userid { get; set; } public virtual applicationuser user { get; set; } public virtual album album { get; set; } }
and use following configuration:
//ef default conventions set albumid foreign key modelbuilder.entity<album>() .hasmany(a=>a.posts) .withrequired(a=>a.album) .willcascadeondelete();
Comments
Post a Comment