简体   繁体   English

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

[英]What's the proper way to update parent/child entities in EF?

I'm using Ef 4 code first and have a parent table with a child 我先使用Ef 4代码,并且有一个带孩子的父表

When I update the parent, I notice that the child is not updated, rather new entries are created (old ones are not deleted). 当我更新父项时,我注意到子项未更新,而是创建了新条目(不删除旧条目)。

My update method looks like so: 我的更新方法如下所示:

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);

If I break out the child properties in the update method like below it solves the duplicate entry problem, but creates other issues elsewhere (primarily with validating null entries). 如果我在如下所示的update方法中分解子属性,它将解决重复条目问题,但会在其他地方(主要是通过验证空条目)造成其他问题。

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

I also tried creating an UpdateChild(), and calling that from UpdateParent(), but got essentially the same result as breaking out the individual child properties 我也尝试创建一个UpdateChild(),并从UpdateParent()调用它,但得到的结果与拆分单个子属性的结果基本相同

Is there a proper way to control this behavior and force EF to overwrite the child entity instead of creating a new one? 是否存在控制此行为并强制EF覆盖子实体而不是创建新实体的正确方法?

在上下文中列出孩子列表,并在不再需要时从您的上下文中删除大孩子。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM