DbContext discard changes without disposing
Solution 1:
public void RejectChanges()
{
foreach (var entry in ChangeTracker.Entries())
{
switch (entry.State)
{
case EntityState.Modified:
case EntityState.Deleted:
entry.State = EntityState.Modified; //Revert changes made to deleted entity.
entry.State = EntityState.Unchanged;
break;
case EntityState.Added:
entry.State = EntityState.Detached;
break;
}
}
}
Update:
Some users suggest to add .ToList()
to avoid 'collection was modified' exception.
But I believe there is a reason for this exception.
How do you get this exception? Probably, you are using context in non threadsafe manner.
Solution 2:
In the simple case of cancelling the changes made to properties of a single entity you can set the current values to the original values.
context.Entry(myEntity).CurrentValues.SetValues(context.Entry(myEntity).OriginalValues);
//you may also need to set back to unmodified -
//I'm unsure if EF will do this automatically
context.Entry(myEntity).State = EntityState.UnModified;
or alternatively reload (but results in db hit)
context.Entry(myEntity).Reload();