在EF中更新父/子实体的正确方法是什么?

时间:2012-05-18 20:33:06

标签: c# entity-framework

我首先使用的是Ef 4代码,并且有一个带有子项的父表

当我更新父级时,我注意到子级未更新,而是创建了新条目(旧条目未被删除)。

我的更新方法如下:

IEFRepository<Parent> repo = new EFRepository<Parent>( context );
var parent = repo.GetSingle(m => m.parentId.Equals(updatedParent.parentId));

parent.Child = updatedParent.Child;  //this is creating a new record in the db, not overwriting the existing

repo.Update(parent);

如果我在更新方法中分解子属性,如下所示它解决了重复输入问题,但在其他地方创建了其他问题(主要是验证空条目)。

parent.Child.property = updatedParent.Child.property;

我还尝试创建一个UpdateChild(),并从UpdateParent()调用它,但得到的结果与打破各个子属性的结果基本相同

是否有正确的方法来控制此行为并强制EF覆盖子实体而不是创建新实体?

1 个答案:

答案 0 :(得分:0)

当您不再需要时,请在上下文中列出子项列表,并在您的上下文中列出remove个孩子。

相关问题