在 EF Core 2 的自引用表中实现级联删除 [英] Implementing Cascade Delete in a self referencing table in EF Core 2

本文介绍了在 EF Core 2 的自引用表中实现级联删除的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在 EF Core 2 的自引用表中实现级联删除(代码优先)?

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; }
}

推荐答案

递归方法解决的问题:

[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);
    }
}

这篇关于在 EF Core 2 的自引用表中实现级联删除的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆