【发布时间】:2016-08-18 18:16:34
【问题描述】:
关于实体框架的问题 - 我正在寻找更新父子记录的更有效方法。
场景 - 我们有一个包含一个或多个子对象的父对象。当父对象更新时,我们需要清除所有当前的子记录并重新添加新的子记录。
例如:
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(record)”行抛出了一个异常,表明存在重复的记录 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 异常以及我们拥有的解决方案是否是处理此问题的最佳方法?
【问题讨论】:
标签: asp.net entity-framework entity-framework-6