在 .NET Core 和 EF Core 中同时更新多个实体的导航属性

问题描述 投票:0回答:0

我有一个已完全定义的关系,但在更新多个导航属性时遇到了问题

家长:

class Parent 
{
    // ...
    public List<ParentItem> items { get; set; }
}

父项目:

class ParentItem 
{
    // ...
    public Parent parent { get; set; }
    public Guid parentId { get; set; }
}

Parent
的实体配置:

builder
    .HasMany(parent => parent.items)
    .WithOne(item => item.parent)
       .HasForeignKey(item => item.parentId);

Child
的实体配置:

builder
    .HasOne(i => i.box)
    .WithMany(b => b.items)
    .HasForeignKey(i => i.boxId)
    .IsRequired();

我要更新的功能:

public IList<BoxItem> GetFromIdList(string sub, IList<Guid> ids)
{
    var query = m_context.items.Where( (i) => i.userId == sub && ids.Contains(i.id));
    return IncludeEntities(query).ToList();
}

public void AssignNewParent(string sub, IList<Guid> itemIds, Guid currentParentId, Guid newParentId)
{
    var itemsToUpdate = GetFromIdList(sub, itemIds).ToList();

    foreach (var item in itemsToUpdate)
    {
       item.parentId = newParentId;
    }

    m_context.SaveChanges();
}

发生了什么:每当我尝试更新多个项目的导航属性时,都会收到以下错误:

System.InvalidOperationException:集合被修改;枚举操作可能无法执行。

在 System.Collections.Generic.Dictionary`2.ValueCollection.Enumerator.MoveNext()

如果我尝试使用相同的代码,而不是针对所有 itemId,而只是对单个实体应用更改,那么一切都会很好。

当我试图了解出了什么问题时,我指的是微软官方文档,但我无法真正弄清楚。

我正在查看的文档 https://learn.microsoft.com/en-us/ef/core/change-tracking/relationship-changes

进一步可以提到的是,如果我不调用

SaveChanges
方法,则不会产生错误。

期待更好地了解这里出了什么问题。感谢所有帮助。

c# .net-core entity-framework-core relationship
© www.soinside.com 2019 - 2024. All rights reserved.