[英]EF6 - updating child objects in a list of parent object causes enumeration error
我需要更新一个对象列表,每个对象都有一个子对象列表。 当我尝试将子对象添加到数据库上下文中时,出现错误消息“修改了集合,可能无法执行枚举操作”。 我试过更改ToList(),这无济于事。 这是一个示例:
public void Update(List<Parent> parents)
{
// I've made this a FOR loop instead of FOREACH - doesn't help
for (int i = 0; i < parents.Count; i++)
{
var parent = parents[i];
var dbEntry = _db.Entry(parent);
dbEntry.State = EntityState.Modified;
foreach (var child in dbEntry.Entity.Children)
if (!parent.Children.Exists(ent => ent.Id == child.Id))
_db.Children.Remove(child);
foreach (var child in parent.Children)
if (child.Id == 0)
dbEntry.Entity.Children.Add(child); <-- ENUMERATION ERROR HERE
}
context.SaveChanges();
}
我到处都在寻找答案,但是找不到答案。 我尝试修复它的所有方法都只能得到相同的结果。 有任何想法吗?
从外观上看,您试图将孩子添加到与您在上一个foreach中迭代的完全相同的大学。
var dbEntry = _db.Entry(parent);
因此
parent = dbEntry.Entity
问题是这个foreach
foreach (var child in parent.Children)
if (child.Id == 0)
dbEntry.Entity.Children.Add(child); <--dbEntry.Entity points to same variable as parent.
在上面的foreach
parent.Children == dbEntry.Entity.Children
如果启用了更改跟踪,并且Parent.Children
属性正确映射,则无需执行任何操作。
如果您禁用了自动更改跟踪,则您可能需要做的就是:
var dbEntry = _db.Entry(parent);
dbEntry.State = EntityState.Modified;
可能,您可能必须遍历每个孩子并将其标记为已添加,例如:
foreach (var child in parent.Children)
if (child.Id == 0) // This is a new Child
_db.Entry(child).State = EntityState.Added
以下if
语句将始终为false!
foreach (var child in dbEntry.Entity.Children)
if (!parent.Children.Exists(ent => ent.Id == child.Id))
如果要删除从列表中删除的子项,但您知道肯定需要不使用AsNoTracking()
。 然后,您应该可以使用_db.Children.Local
属性,因为它将包含您检索到的所有实体。 但是请确保您检查该孩子是否存在于List<Parents>
任何一个中,否则您可能正试图删除已转换父母(例如被收养)的孩子。
您能告诉我为什么要手动管理此状态吗?
为什么不让EF为您跟踪状态变化? 然后,您无需担心,只需要在其他地方添加/删除实际的子代,然后只需调用_db.SaveChanges()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.