Deatch
doesn't fully undo the changes. Per the msdn doc "Only the entity is removed; if there are any related objects that are being tracked by the same ObjectStateManager, those will not be detached automatically."
Only the entity you pass to detach is removed. Other changes will cause a failure. Will there be contention for you db? If this application is the only thing making changes to the db you can undo changes with context.Refresh(RefreshMode.StoreWins, object);
otherwise, it's a bit more complicated.
You have to do something like this;
var entry = context.ObjectStateManager.GetObjectStateEntry(((IEntityWithKey)object).EntityKey);
for (int i = 0; i < entry.OriginalValues.FieldCount; i++)
{
entry.CurrentValues.SetValue(i, entry.OriginalValues[i]);
}
entry.AcceptChanges();
The above code uses the ObjectSateManager
to return all modified objects to their original states, after that context.SaveChanges();
shoudl succeed.
You may also find this useful http://dotnetadventurer.blogspot.com/2010/09/discarding-changes-to-objectcontext-in.html I haven't tried his code and I usually initialize my context differently so I'm not sure if it will work with your example but it's very simple so if it does, it's the route I would go.