【问题标题】:What's the proper way to update parent/child entities in EF?在 EF 中更新父/子实体的正确方法是什么?
【发布时间】:2012-05-18 20:33:06
【问题描述】:

我首先使用 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 覆盖子实体而不是创建新实体?

【问题讨论】:

  • 您能否详细说明您正在尝试进行的更改?从这个描述很难理解,至少对我来说是这样。 :)

标签: c# entity-framework


【解决方案1】:

当您不再需要时,拥有上下文中的子项列表和上下文中的 remove 旧子项。

【讨论】:

    猜你喜欢
    • 2015-06-03
    • 2022-09-23
    • 1970-01-01
    • 1970-01-01
    • 2015-01-26
    • 1970-01-01
    • 1970-01-01
    • 2013-03-03
    • 1970-01-01
    相关资源
    最近更新 更多