【发布时间】:2011-06-07 04:43:18
【问题描述】:
我需要将多个子对象添加到现有的父对象。我正在实例化我的父对象并在我的 UI 处理层(将添加我的子对象)中设置它的 Key/Id。
Parent parenttoModify = new Parent();
parenttoModify.Parent_Id = 5; //this comes from some Index of a dropdown or a key column of a grid, i Have put a dummy value here for example
parenttoModify.Children.Add(child);
parenttoModify.Children.Add(child2);
DataAccess.ModifyParent(parenttoModify);
在我的数据访问层中,我有一个类似的方法:
public static bool ModifyParent(Parent parent)
{
int recordsAffected=0;
using (TestEntities testContext = new TestEntities())
{
testContext.Parents.Attach(parent);
var parentEntry = testContext.ObjectStateManager.GetObjectStateEntry(parent);
parentEntry.ChangeState(System.Data.EntityState.Modified);
recordsAffected = testContext.SaveChanges();
}
return recordsAffected > 0 ? true : false;
}
调用 testContext.Parent.Attach(parent) 时出现错误。它说:
具有相同键的对象已经存在。
我不确定为什么会发生这种情况,因为我没有添加父对象,我只是附加它并在其中添加子对象。
知道我哪里出错了吗?
【问题讨论】:
标签: asp.net entity-framework ado.net