c# - ASP.NET MVC. How manually add "cascade delete" to a code first relationship? -
how configure cascade delete code first project without setting navigation properties [required] or non nullable ?
for instance:
class mainclass{ [key] int id {get;set;} public string name {get;set;} public virtual icollection<subitem> subitems {get;set} }
and
class subitem{ [key] int id {get; set;} public string name {get;set;} }
deleting main class should delete related subitems
to have cascade deletes on nullable foreign keys through code first set up, best way achieve through fluent api.
add fluent api code dbcontext:
protected override void onmodelcreating(dbmodelbuilder modelbuilder) { modelbuilder.entity<subitem>() .hasoptional(o => o.mainclass) .withmany(m => m.subitems) .hasforeignkey(k => k.mainclassid) .willcascadeondelete(true); }
and subitem class needs updated these properties:
class subitem { [key] int id {get; set;} public string name {get;set;} public int? mainclassid { get; set;} public virtual mainclass mainclass { get; set; } }
i believe if deleting mainclass item subitems must loaded in context (using include statement when pulling mainclass object) deleted.
but if go database , set foreign key have cascade on delete enabled, not have have subitems loaded context because database take care of cascade deleting when mainclass object deleted.
Comments
Post a Comment