14

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.

5 Answers 5

22

What about changing the ObjectState?

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

From MSDN: ObjectStateManager.ChangeObjectState Method.

2
  • 9
    In the spirit of keeping this answer current, with EF6 its context.Entry(job).State = System.Data.Entity.EntityState.Modified
    – matto0
    Apr 6, 2015 at 21:06
  • 1
    EF's API is like talking to brick wall.
    – A.R.
    Nov 6, 2015 at 16:55
3

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

0
2

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.

1

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();
1
  • var job = context.Jobs.SingleOrDefault(p => p.Id == id);
    – jolySoft
    May 21, 2015 at 14:27
1

My issue was that I was attaching after I updated the object, when in-fact, you have to attach BEFORE you update any properties

context.Table.Attach(object);
object.MyProperty = "new value";
context.Table.SaveChanges();
1
  • If you have changed entity before attaching then you can also do context.Entry(object).State = System.Data.Entity.EntityState.Modified before the SaveChanges in order to update the ChangeTracker to indicate that the specific object has changed. learn.microsoft.com/en-us/ef/ef6/saving/change-tracking/…
    – Sebastian
    Jun 10, 2022 at 13:07

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.