簡體   English   中英

在EF Core 2的自引用表中實現級聯刪除

[英]Implementing Cascade Delete in a self referencing table in EF Core 2

如何在EF Core 2(代碼優先)的自引用表中實現Cascade Delete?

(例如,有一個“評論表”,男人可以回復評論,而這個回復可以由另一個人回復。)

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM