c# - Cascading delete with Entity Framework -


i have comments table contains amongst other things columns id - id of comment, commenter_id id of user posted it, , parentcomment_id self referencing foreign key. there 2 levels commenting, parents , sub comments. if comment record has parentcomment_id of null, parent comment.

i'm trying write expression delete comments user, causing problems because of self reference mentioned earlier.

take records sample example of problem:

user id 2 posted comment, id of 3. because parent comment has parentcomment_id value of null. later on, user id 1 responds comment sub-comment, creating comment 7 (there other comments/subcomments between these 2 hence id increment jump).

i'm not able delete comment id 3 because sub comment, comment id 7, has foreign key it.

currently entity framework statement trying delete comments follows:

context.comments.where(x => x.commenter.id == user.id).delete(); 

but gives me exception because of described problem.

i fix using few foreach loops, hoping there easier way context.cascade().where(.... wondering delete() method part of entityframework.extended package.

if have entity this:

public class comment {   public int id{get;set;}   public int? parentcommentid{get;set;}    public virtual comment parentcomment{get;set;}   public virtual icollection<comment> comments{get;set;} } 

you try configuration:

protected override void onmodelcreating(dbmodelbuilder modelbuilder) {     modelbuilder.entity<comment>()                 .hasoptional(c=>c.parentcomment)                 .withmany(c=>c.comments)                 .hasforeignkey(c => c.parentcommentid)                  .willcascadeondelete(true); } 

you can configure cascade delete on relationship using willcascadeondelete method.if foreign key on dependent entity is nullable, code first does not set cascade delete on relationship, , when principal deleted foreign key set null.


Comments

Popular posts from this blog

python - TypeError: start must be a integer -

c# - DevExpress RepositoryItemComboBox BackColor property ignored -

django - Creating multiple model instances in DRF3 -