实体框架在更新父级时更新子级
我将父级及其子级发送到我的服务层。
该模型的设置如下:
public class Parent
{
public int ParentId { get; set; }
public ICollection<Child> Children;
}
public class Child
{
public int ChildID {get; set;}
public virtual Parent Parent{get;set}
public virtual int ParentId{get; set;}
public string FirstName { get; set; }
}
我想要的行为是子级始终附加到父级,因此如果子级在数据库中未找到附加的,我们应该将其删除。如果不存在,则创建它。如果存在,请更新它。
如何在不编写代码来手动进行所有这些调用的情况下完成此任务?就像删除所有,然后重新添加所有。
I'm sending both parent and its children to be updated to my service layer.
The model is set up as follows:
public class Parent
{
public int ParentId { get; set; }
public ICollection<Child> Children;
}
public class Child
{
public int ChildID {get; set;}
public virtual Parent Parent{get;set}
public virtual int ParentId{get; set;}
public string FirstName { get; set; }
}
The behaviour I'd like is that the children are always attached to the parent, so if a child is in the database that is not found attached, we should remove it. If it does not exist, create it. If it exist, update it.
How do I accomplish this without writing code to make all these calls manually? Like remove all, then re-add all.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您不需要删除所有子项并重新添加它们(如果数据库中有其他实体引用您只想更新的子项之一,这无论如何都可能是一个问题。删除并重新添加它将导致违反外键约束)。
您实际上需要做的更复杂:(
您必须在数据库中加载原始对象图,然后逐个子项检查它是否已被删除,是否是新的或是否已存在。
一个非常适合的示例你的模型在这里:
无法更改关系,因为一个或多个外键属性不可为 null
实体框架不支持您使用分离对象更新数据库中的对象图它提供的唯一支持是更新标量和复杂属性,您可以使用
ApplyCurrentChanges
(对于ObjectContext
)或Entry(entity).CurrentValues.SetValues。
(对于DbContext
)。后者在链接的示例中用于更新父级和每个子级的标量属性,但更新实体之间的关系是一项手动任务。You don't need to remove all children and re-add them (which can be a problem anyway if you have for example other entities in the database which refer to one of the children you only want to update. Deleting and re-adding it would lead to a foreign key constraint violation).
What you actually need to do is more complicated :(
You must load the original object graph in the database and then check child by child if it has been deleted, if it is new or if it already exists.
An example which fits quite exactly to your model is here:
The relationship could not be changed because one or more of the foreign-key properties is non-nullable
Entity Framework doesn't support you to update an object graph in the database with a detached object graph. The only support it offers is updating scalar and complex properties. For those you can use
ApplyCurrentChanges
(forObjectContext
) orEntry(entity).CurrentValues.SetValues
(forDbContext
). The latter is used in the linked example to update the parent`s and each child's scalar properties. But updating relationships between entities is a manual task.