15

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.

Shawn Mclean
  • 56,733
  • 95
  • 279
  • 406

5 Answers5

22

What about changing the ObjectState?

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

From MSDN: ObjectStateManager.ChangeObjectState Method.

CD..
  • 72,281
  • 25
  • 154
  • 163
3

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

Community
  • 1
  • 1
Ladislav Mrnka
  • 360,892
  • 59
  • 660
  • 670
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.

sming
  • 801
  • 2
  • 12
  • 25
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();
Muhammad Soliman
  • 21,644
  • 6
  • 109
  • 75
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();
Kellen Stuart
  • 7,775
  • 7
  • 59
  • 82
  • 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. https://learn.microsoft.com/en-us/ef/ef6/saving/change-tracking/entity-state#attaching-an-existing-but-modified-entity-to-the-context – Sebastian Jun 10 '22 at 13:07