DbContext discard changes without disposing

Raheel Khan picture Raheel Khan · May 8, 2013 · Viewed 42.9k times · Source

I have a desktop client application that uses modal windows to set properties for hierarchical objects. Since this is a client application and access to the DbContext is not threaded, I use a long-running context on the main Form that gets passed around to modal children.

These modal windows use the PropertyGrid to display entity properties and also have cancel buttons. If any data is modified and the cancel button is pressed, the changes are reflected in the parent form (where I cannot dispose the DbContext object).

Is there a way to discard any changes made if the DbContext.SaveChanges() method has NOT been called?

UPDATE: Entity Framework Version 4.4.

Answer

Sergey Shuvalov picture Sergey Shuvalov · Feb 28, 2014
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.