【发布时间】:2013-09-24 14:25:54
【问题描述】:
我有一个嵌套的 EF 对象挂在其父对象上。 1:n关系
[父]-[n..child]
嵌套对象子对象是动态的,将通过 GUI 更新。
我在数据库上更新它时遇到问题。
错误信息: ObjectStateManager 中已存在具有相同键的对象。 ObjectStateManager 无法跟踪具有相同键的多个对象。
这是第二版的问题。我对判断 preExist 的 if 块进行了更正
提前感谢您的帮助
坐鸭
主要更新
void MainUpdate
{
var context = new FamilyEntities();
parent = getParentFromGui();
parent.UpdateRelatedEntities(context);
context.dispose();
}
对象父对象已在 Gui 中更新
parent getParentFromGui()
{
parent myParent = parentBindingSource.DataSource as parent;
foreach(child c in childrenBindingSource)
{
myParent.children.Add(c);
}
return myParent
}
修改 UpdateRelatedEntities
public static void UpdateRelatedEntities(this parent entity, FamilyEntities context)
{
if (entity == null) return;
var res = context.parent.Where(x => x.uid_parent == entity.uid_parent);
var rec = res.FirstOrDefault();
context.parent.Attach(rec);
context.parent.ApplyCurrentValues(entity);
foreach (var c in entity.children)
{
bool preExist = context.children.FirstOrDefault(x => x.child_uid == c.child_uid);
if (preExist != null)
{
context.children.Attach(obj);
context.children.ApplyCurrentValues(c);
}
else
{
// This Part throw ERROR
context.children.AddObject(c);
}
}
context.SaveChanges();
}
我做错了什么?
发送很多!
【问题讨论】:
-
context.shaft_section 是什么?这是否保证孩子不在 children 集合中?
-
ups 抱歉,应该是儿童版。感谢指正
-
现在您正在检查一个集合是否等于集合中的一个项目。这应该总是错误的。像 context.children.Any(x => x.child_uid == c.child_uid) 这样的东西应该可以工作
标签: c# entity-framework entity-framework-4