Implementing Cascade Delete in a self referencing table in EF Core 2

cascade ef-core-2.0 ef-migrations entity-framework entity-framework-core

Question

How can I implement Cascade Delete in a self referencing table in EF Core 2 (code first)?

(For example there is a Comment Table and man can reply to a comment and this reply can reply by another.)

public class Comment
{
    public virtual int Id { get; set; }
    public virtual int? ParentId { get; set; }
    public Comment Parent { get; set; }
    public virtual IList<Comment> Replies { get; set; }
    public virtual string Description { get; set; }
    public virtual Article Article { get; set; }
}

enter image description here

1
1
3/10/2018 5:24:45 PM

Accepted Answer

The problem solved by recursive method:

[HttpPost]
public async Task<JsonResult> DeleteComment([FromBody] DeleteCommentViewModel obj)
{
    if (ModelState.IsValid)
    {
       var comment = await 
      _commentRepository.GetAll().SingleOrDefaultAsync(m => m.Id == obj.CommentId);
      if (comment != null)
      {
          await RemoveChildren(comment.Id);
         _commentRepository.Delete(comment);
      }
      if (Request.IsAjaxRequest())
      {
          return Json(1);
      }
   }
   return Json(new { code = 0 });
}


async Task RemoveChildren(int i)
{
    var children = await _commentRepository.GetAll().Where(c => c.ParentId = i).ToListAsync();
        foreach (var child in children)
    {
       await RemoveChildren(child.Id);
       _commentRepository.Delete(child);
    }
}
3
3/11/2018 4:00:13 PM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow