How to update entities which are modified outside the DbContext?

独自空忆成欢 提交于 2019-11-28 21:35:01
StuartLC

You also need to tell EF that the entity is modified, after attaching it.

context.Entry(specificationToSave).State = EntityState.Modified;

Alternatively, you can make the changes to the entity after you have reattached it, e.g. see MVC3 with EF 4.1 and EntityState.Modified

Edit

You can use generics with DbSet - either class, or method - as follows:

    public void Update<TEntity>(TEntity entity)
    {
        DbContext.Set<TEntity>().Attach(entity);
        DbContext.Entry(entity).State = EntityState.Modified;
        DbContext.SaveChanges();
    }

Edit : For updating of detached Parent / Child Graphs

For updating of simple / shallow parent-child relationships where efficiency and performance is not important, simply deleting all old children and reinserting the new ones is an easy (although ugly) solution.

However, for a more efficient scenario requires us to traverse the graph, detect changes, and then add newly inserted, update existing, ignore unchanged, and delete removed items from the Context.

Slauma shows a great example of this here.

You might want to look at using GraphDiff, which can do all this leg work for you!

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