Force EF 4.1 Code First to See an Attached entity as Modified

故事扮演 提交于 2019-11-30 04:54:54
Morteza Manavi

When you Attach an entity, it goes to Unchanged state (it has not been changed since it attached to the context). All you need to is to explicitly change the Entity State to Modified:

_context.Users.Attach(user);
_context.Entry(user).State = System.Data.Entity.EntityState.Modified;
_context.SaveChanges();

For the sake of completeness, you can access the ObjectContext by casting the DbContext to IObjectContextAdapter:

((IObjectContextAdapter)context).ObjectContext.ObjectStateManager.ChangeObjectState(user, EntityState.Modified);

Morteza's method is much cleaner though and gets my vote.

zeeshanhirani

I believe u do not need to attach the entity before u call modified. simply setting to modified will do the job.

if (_context.Entry(user).State == EntityState.Detached)
{
    _context.Entry(user).State = EntityState.Modified;
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!