Exception:The object cannot be attached because it is already in the object context
.net, entity-framework
Solution
IF this happens all in the context of a single `DbContext` (or `ObjectContext`) - just select the record, update the fields you want, and keep going. Once you've updated all records - then call `.SaveChanges()` once. No need for `Attach` or the `ChangeObjectState` calls.....
var data = userDetails.users.Where(x => x.IsAnonymous == true);
foreach(var item in data)
{
var updatedData = db.Users.FirstOrDefault(x => x.UserId == item.UserId);
if(updatedData != null)
{
updatedData.IsAnonymous = true;
}
}
db.SaveChanges();
Since you've just selected `updatedData` from the `db.Users` set of data - it's already part of the object set - no need to attach it again! Just update what you need, and call `.SaveChanges()` (preferably once for the whole batch - not once per record...)
Problem
I am trying to update records in a loop using Entity Framework like this: ``` var data = userDetails.users.Where(x => x.IsAnonymous == true); foreach(var item in data) { var updatedData = db.Users.FirstOrDefault(x => x.UserId == item.UserId); updatedData.IsAnonymous = true; db.Users.Attach(updatedData); db.ObjectStateManager.ChangeObjectState(updatedData, EntityState.Modified); db.SaveChanges(); } ``` While attach (`db.Users.Attach(updatedData);`) I got exception The object cannot be attached because it is already in the object context. An object can only be reattached when it is in an unchanged state How can I resolve this error?