Entity framework attach update not working

懵懂的女人 提交于 2019-12-03 10:36:55

What about changing the ObjectState?

context.ObjectStateManager.ChangeObjectState(job, System.Data.EntityState.Modified);

From MSDN: ObjectStateManager.ChangeObjectState Method.

Ladislav Mrnka

I guess you are working with detached object - check second part of this answer.

you have to get the job first then you could successfully update it, chk below snippet

  var job = context.Jobs.Where(p => p.Id == id).FirstOrDefault();
//apply your changes
job.Title = "XXXX";
///....
context.SaveChanges();

another reason that this may not work is when the corresponding Jobs.cs file has been committed but the .edmx file has not. This means that the property is present but not mapped and therefore EF does not consider the object modified. For example:

...
using (var dao = new DbContext())
{
    dao.Jobs.Attach(job);
    job.SomeProperty = 1234; // SomeProperty exists but is not in the .edmx
    dao.SaveChanges();
}

if SomeProperty is present in Jobs.cs but missing from the .edmx file, this code will compile and execute without a hint that anything is wrong but SomeProperty will not be updated in the Database. Took me the best part of a day to find this one.

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