Search code examples
c#.netentity-frameworkdbcontextundo

DbContext discard changes without disposing


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.


Solution

  • How about wrapping it in a transaction?

        using(var scope = new TransactionScope(TransactionScopeOption.Required,
            new TransactionOptions { IsolationLevel = IsolationLevel.ReadCommitted })){
    
            // Do something 
            context.SaveChanges();
            // Do something else
            context.SaveChanges();
    
            scope.Complete();
    }