Entity framework attach update not working

Deadly 提交于 2019-12-04 16:51:17

问题


I'm trying to update a POCO object using entity framework in the following way:

 context.Jobs.Attach(job);
 context.SaveChanges();

That does not work. No error is thrown, it just isn't updating the values in the database.

I tried:

context.Jobs.AttachTo("Jobs", job);
context.SaveChanges();

Nothing wrongs, still no error and no updates.


回答1:


What about changing the ObjectState?

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

From MSDN: ObjectStateManager.ChangeObjectState Method.




回答2:


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




回答3:


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



回答4:


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.



来源:https://stackoverflow.com/questions/4728212/entity-framework-attach-update-not-working

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