EF 4.3 CF does not update relationships when saving changes

Deadly 提交于 2020-01-17 12:27:09

问题


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

回答1:


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



来源:https://stackoverflow.com/questions/11074662/ef-4-3-cf-does-not-update-relationships-when-saving-changes

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!