gpt4 book ai didi

entity-framework - 在 EF Core 2 的自引用表中实现级联删除

转载 作者:行者123 更新时间:2023-12-02 20:29:21 25 4
gpt4 key购买 nike

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

(例如有一个评论表,一个人可以回复一个评论,这个回复可以被另一个人回复。)

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

最佳答案

递归方法解决的问题:

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

关于entity-framework - 在 EF Core 2 的自引用表中实现级联删除,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49211561/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com