Kumar
Kumar

Reputation: 11349

EF entity.attach does not work

I have an entity retrieved from db as follows

using ( var ctx = new Mycontext() )
   return ctx.MyGroups.First( // query );

this is bound to UI and updated on user save action as follows

using ( var ctx = new Mycontext() )
{
    ctx.MyGroups.Attach(o); // verified object o is updated 
    ctx.SaveChanges();

}

However the db is NOT updated

Environment is .net 4.0, db is sql compact 4

Any help on what could be missing/wrong ?

Upvotes: 4

Views: 3159

Answers (3)

Dejan Janjušević
Dejan Janjušević

Reputation: 3230

As suggested by Ciobanu Ion, here is your solution:

using ( var ctx = new Mycontext() ) 
{ 
    ctx.MyGroups.Attach(o); // verified object o is updated  
    ctx.ObjectStateManager.ChangeObjectState(o, EntityState.Modified);
    ctx.SaveChanges(); 

} 

EDIT As of EF 6, the above solution doesn't work. Instead, use the following:

using ( var ctx = new Mycontext() )
{
    ctx.MyGroups.Attach(o); // verified object o is updated 
    ctx.Entry(entity).State = EntityState.Modified;
    ctx.SaveChanges();
}

Upvotes: 0

Ion Ciobanu
Ion Ciobanu

Reputation: 506

When you attach objects to the context, their default state is Unchanged, you should force the update by setting DBContext.Entry(entity).State = EntityState.Modified; And only after that call DBContext.SaveChanges();

Upvotes: 11

Muhammad Adeel Zahid
Muhammad Adeel Zahid

Reputation: 17784

Attach method relies on primary key to attach the entity to object context. What seems to me is that when your object is changed from the view and model bound your primary key value is missing in the updated object.

Upvotes: 0

Related Questions