保存更改时,EF 4.3 CF不会更新关系 [英] EF 4.3 CF does not update relationships when saving changes
问题描述
public virtual void Update(IEntity entityToUpdate)
{
DbSet.Attach(entityToUpdate);
Context.Entry(entityToUpdate).State = EntityState.Modified;
SaveChanges();
}
在具体情况下,您可以可能只是删除附加
行。 附加
将包含其他分离实体的分离实体放在对象图形中,进入状态不变
。当您将状态更改为修改
时,它仅影响父实体,孩子仍然处于状态不变
。如果您调用 SaveChanges
,则不会保存子项,因为它们的状态为不变
。
如果您不调用附加
,孩子们保持分离,直到 SaveChanges
被调用在哪里EF将假定它们是新实体(因为它们不附加到上下文),并将其状态设置为添加
。然后他们将被插入数据库。
但是,如果删除 Attach
行,则无法使用该方法更新现有的父母和现有孩子之间的关系。
通常,当分离的实体包含已更改的实体的子集合时,添加了实体已被删除的位置从您通常必须从数据库重新加载原始对象图并将更改合并到其中。复杂分离对象图的这种更新不以通用方式工作,并且将需要实体类型特定的代码。例如: https://stackoverflow.com/a/5540956/270591
I've got a ClubItem object with a relationship collection ICollection ClubUsers. I load a ClubItem from the context and add a couple of new users to the CluItem. When saving the ClubItem in a disconnected state the context does not see the new ClubUsers as new entities. How to tell the context that something changed? I allready use this to change entitystate of the ClubItem:
public virtual void Update(IEntity entityToUpdate)
{
DbSet.Attach(entityToUpdate);
Context.Entry(entityToUpdate).State = EntityState.Modified;
SaveChanges();
}
In your specific case you can probably just remove the Attach
line. Attach
puts the detached entity including other detached entities in the object graph into state Unchanged
. When you change the state to Modified
it affects only the parent entity, the children are still in state Unchanged
. If you call SaveChanges
the children won't be saved because their state is Unchanged
.
If you don't call Attach
the children stay detached until SaveChanges
is called where EF will assume that they are new entities (because they are not attached to the context) and set their state to Added
. Then they will be inserted into the database.
However, if you remove the Attach
line you cannot use the method anymore to update the relationship between existing parent and existing children.
Generally, when the detached entity contains a child collection of entities that are changed, added of where entities have been removed from you normally have to reload the original object graph from the database and merge the changes into it. Such an Update of a complex detached object graph does not work in a generic way and will require entity type specific code. An example is here: https://stackoverflow.com/a/5540956/270591
这篇关于保存更改时,EF 4.3 CF不会更新关系的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!