0
实体框架问题 - 我正在寻找更有效的方式来更新父和子记录。ASP.NET实体框架 - 使用附件更新子依赖项
场景 - 我们有一个包含一个或多个子对象的父对象。当父对象得到更新时,我们需要清除所有当前的子记录并重新添加新的子记录。
例如:
public bool UpdateProfile(Parent record)
{
try
{
_context.Parent.Attach(record);
_context.Entry(record).State = EntityState.Modified;
List<Child> childrenToDelete = GetChildrenByParentId(parent.Id);
foreach (Child child in childrenToDelete)
{
_context.Child.Remove(child);
_context.Entry(child).State = EntityState.Deleted;
}
foreach (Child child in record.children)
{
_context.ProfileCategories.Add(child);
}
_context.SaveChanges();
return true;
}
...
}
上述代码在“_context.Parent.Attach(记录)”行抛出异常说,有记录的重复的ID。所以我们的工作是:
public bool UpdateProfile(Parent record)
{
try
{
var originalChildren = record.children;
record.children = new List<Child>();
_context.Parent.Attach(record);
_context.Entry(record).State = EntityState.Modified;
_context.SaveChanges();
List<Child> childrenToDelete = GetChildrenByParentId(parent.Id);
foreach (Child child in childrenToDelete)
{
_context.Child.Remove(child);
_context.Entry(child).State = EntityState.Deleted;
}
foreach (Child child in originalChildren)
{
_context.ProfileCategories.Add(child);
}
_context.SaveChanges();
return true;
}
...
}
这第二块代码的作品,但我只是觉得它不理想。
任何人都可以告诉我们为什么Attach会抛出重复的Id异常,如果我们拥有的解决方案是处理此问题的最佳方法?