Entity framework attach update not working
Asked Answered
D

5

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.

Dyarchy answered 18/1, 2011 at 19:35 Comment(0)
S
22

What about changing the ObjectState?

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

From MSDN: ObjectStateManager.ChangeObjectState Method.

Semipro answered 18/1, 2011 at 20:18 Comment(2)
In the spirit of keeping this answer current, with EF6 its context.Entry(job).State = System.Data.Entity.EntityState.ModifiedArabel
EF's API is like talking to brick wall.Nova
R
3

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

Rumery answered 18/1, 2011 at 20:18 Comment(0)
B
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.

Baggs answered 7/10, 2014 at 19:47 Comment(0)
R
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();
Retroflex answered 19/2, 2013 at 18:54 Comment(2)
var job = context.Jobs.SingleOrDefault(p => p.Id == id);Withoutdoors
This only works if you use auto tracking. If you don't use auto tracking, then you have to attach it yourself... leading to the problem of the original post.Slogan
H
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();
Hudak answered 15/10, 2020 at 16:44 Comment(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/…Blackwood

© 2022 - 2024 — McMap. All rights reserved.