在删除所有指向它的“主题”行后,删除“论坛”行时,出现DbUpdateConcurrencyException。为什么?

时间:2019-12-30 14:55:14

标签: c# asp.net-core-mvc entity-framework-core

因此,我正在做这个论坛项目,以便在学习过程中学习.net core / c#中的各种内容。现在,我正在实现删除给定论坛及其所有子论坛,主题和帖子的功能(由于级联,它们会自动处理)。

我可以删除子论坛,但是当我尝试删除论坛本身时,会收到DbUpdateConcurrencyException。如果在不再有任何子论坛的情况下尝试执行该操作,则会成功。

如您所见,Forum.ChildForums是一个逆属性,因此它不存储在数据库本身中。当我删除子论坛时,论坛本身的数据库中没有任何更改,对吧?

此外,.Delete()函数来自Entity Framework Plus。

我的论坛模型课程:

public class Forum
{
    public enum ForumType
    {
        Category, Forum
    }

    [Key]
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public int Id { get; set; }
    public string Name { get; set; }
    public string Description { get; set; }
    public Category Category { get; set; }
    [InverseProperty("ParentForum")]
    public List<Forum> ChildForums { get; set; }
    public Forum ParentForum { get; set; }
    public ForumType Type { get; set; }
    [InverseProperty(nameof(Topic.Forum))]
    public List<Topic> Topics { get; set; }
    [NotMapped]
    public int TopicCount { get; set; }
    [NotMapped]
    public int PostCount { get; set; }
    [NotMapped]
    public Post LastPost { get; set; }
}

发生故障的控制器:

public IActionResult Delete(int forumId)
{
    Forum forum = _db.Forum.Include(f => f.ParentForum).Include(f => f.ChildForums).Where(f => f.Id == forumId).FirstOrDefault();

    switch (forum.Type)
    {            
        case Forum.ForumType.Forum:
            _db.Topic.Where(t => t.Forum == forum).Delete();
            break;


        case Forum.ForumType.Category:
        default:
            foreach(var childForum in forum.ChildForums)
            {
                _db.Topic.Where(t => t.Forum == childForum).Delete();
            }

            _db.Forum.Where(f => f.ParentForum == forum).Delete();
            break;
    }

    int parentForumId = (forum.ParentForum != null && forum.ParentForum.Id != 0) ? forum.ParentForum.Id : 0;

    _db.Forum.Remove(forum); // An exception is thrown at this point, if any child forums were removed
    _db.SaveChanges();

    if (parentForumId != 0)
    {
        return RedirectToAction(nameof(ForumController.Index), new { categoryId = parentForumId});
    }
    else
    {
        return RedirectToAction(nameof(ForumsController.Index));
    }
}

我想我可以一路爬到顶端(论坛),但是很高兴能确切地理解为什么我会收到此异常,并知道执行此操作的正确方法。 (就像我说的那样,我正在尝试在这里学习)

0 个答案:

没有答案