DbContext discard changes without disposing

47,863

Solution 1

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();
}

Solution 2

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 3

This is based on Surgey Shuvalov's answer. It adds support for navigation property changes.

public void RejectChanges()
{
    RejectScalarChanges();
    RejectNavigationChanges();
}

private void RejectScalarChanges()
{
    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;
        }
    }
}

private void RejectNavigationChanges()
{
    var objectContext = ((IObjectContextAdapter)this).ObjectContext;
    var deletedRelationships = objectContext.ObjectStateManager.GetObjectStateEntries(EntityState.Deleted).Where(e => e.IsRelationship && !this.RelationshipContainsKeyEntry(e));
    var addedRelationships = objectContext.ObjectStateManager.GetObjectStateEntries(EntityState.Added).Where(e => e.IsRelationship);

    foreach (var relationship in addedRelationships)
        relationship.Delete();

    foreach (var relationship in deletedRelationships)
        relationship.ChangeState(EntityState.Unchanged);
}

private bool RelationshipContainsKeyEntry(System.Data.Entity.Core.Objects.ObjectStateEntry stateEntry)
{
    //prevent exception: "Cannot change state of a relationship if one of the ends of the relationship is a KeyEntry"
    //I haven't been able to find the conditions under which this happens, but it sometimes does.
    var objectContext = ((IObjectContextAdapter)this).ObjectContext;
    var keys = new[] { stateEntry.OriginalValues[0], stateEntry.OriginalValues[1] };
    return keys.Any(key => objectContext.ObjectStateManager.GetObjectStateEntry(key).Entity == null);
}

Solution 4

You colud try to do it manually, something like this.. not sure this works for your scenario but you can give it a try:

public void UndoAll(DbContext context)
    {
        //detect all changes (probably not required if AutoDetectChanges is set to true)
        context.ChangeTracker.DetectChanges();

        //get all entries that are changed
        var entries = context.ChangeTracker.Entries().Where(e => e.State != EntityState.Unchanged).ToList();

        //somehow try to discard changes on every entry
        foreach (var dbEntityEntry in entries)
        {
            var entity = dbEntityEntry.Entity;

            if (entity == null) continue;

            if (dbEntityEntry.State == EntityState.Added)
            {
                //if entity is in Added state, remove it. (there will be problems with Set methods if entity is of proxy type, in that case you need entity base type
                var set = context.Set(entity.GeType());
                set.Remove(entity);
            }
            else if (dbEntityEntry.State == EntityState.Modified)
            {
                //entity is modified... you can set it to Unchanged or Reload it form Db??
                dbEntityEntry.Reload();
            }
            else if (dbEntityEntry.State == EntityState.Deleted)
                //entity is deleted... not sure what would be the right thing to do with it... set it to Modifed or Unchanged
                dbEntityEntry.State = EntityState.Modified;                
        }
    }

Solution 5

You can apply this:

context.Entry(TEntity).Reload();

I try it and its work well for me.

Note: This method (Reload) Reloads the entity from the database overwriting any property values with values from the database. The entity will be in the Unchanged state after calling this method.

Share:
47,863
Raheel Khan
Author by

Raheel Khan

Debugging is twice as hard as writing the code in the first place. Therefore, if you write the code as cleverly as possible, you are, by definition, not smart enough to debug it. - Brian Kernighan

Updated on June 15, 2021

Comments

  • Raheel Khan
    Raheel Khan almost 3 years

    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.

  • Daniel
    Daniel about 10 years
    This is very good. The only thing I changed was that in case of a deleted entity setting the entityState to modified will not cut it. Instead dbEntityEntry.Reload(); will provide the required effect (just as in case of a modified entity).
  • MaxVerro
    MaxVerro over 8 years
    In the Entity.Modified Case you don't need to set the CurrentValues to the OriginalValues. Changing the state to Unchanged will do it for you ^.^!
  • Raheel Khan
    Raheel Khan about 8 years
    I have to +1 this answer simply because too many questions have been asked about the effects of calling context.SaveChanges multiple times within a transaction. This does not however, address the core question.
  • Raheel Khan
    Raheel Khan over 7 years
    Took a while but this is what we ended up using. @Gert Arnold's comment on the question should be noted as the best practice though.
  • Dasith Wijes
    Dasith Wijes over 7 years
    Nor will it refresh other connected entities through foreign keys.
  • Jerther
    Jerther over 6 years
    See my answer. It adds support for navigation property changes to this excellent answer.
  • Raheel Khan
    Raheel Khan about 6 years
    I can't test at the moment but, perhaps you could try calling ChangeTracker.Entries() before disabling tracking.
  • Evgeny
    Evgeny about 6 years
    It crashes... I have to scrap all this, does not work on other scenarious
  • T M
    T M over 5 years
    For me this was throwing "collection was modified .. " exception. Changed ChangeTracker.Entries() to ChangeTracker.Entries().ToList() to avoid the exception.
  • Marco Luzzara
    Marco Luzzara over 5 years
    The exception related to KeyEntry is thrown when Entity property is null. It is defined like this: get { return null == this._wrappedEntity; } from the disassembled module.
  • Jerther
    Jerther over 5 years
    With all the improvements we're bringing on the original code, I think it would be worth a new project on github along with a NuGet package. Just an idea though as I don't work with EF anymore.
  • RouR
    RouR about 5 years
    context.TEntity.Local.Clear(); stackoverflow.com/questions/5466677/…
  • Captain Prinny
    Captain Prinny over 4 years
    Doesn't have to be in a non threadsafe manner. Using it purely synchronously in EFCore
  • Bamdad
    Bamdad over 3 years
    @Daniel well it will cause a connection to db and may not be performant when you have a lot of deleted entities. Can you suggest an alternative?
  • Gert Arnold
    Gert Arnold almost 3 years
    No, this only clears the change tracker. Not the changes in the entities. Also, now all entities must be re-attached to save any new changes. This doesn't solve OP's problem.
  • Ziad Akiki
    Ziad Akiki almost 3 years
    @GertArnold Here's an example where this could be helpful: Say you're saving some records to the database and it failed due to a certain error. You are logging your errors into the DB within a middleware, so you need to disregard any failure that occurs and insert a error log entry within the log table using the same DB context in order not to create a new instance. So you clear all the changes like this not caring about the data since you'll be saving an error log entry and returning an error response.
  • Gert Arnold
    Gert Arnold almost 3 years
    All well and good, but this doesn't "discard any changes made" as OP wants. You're answering from your own frame of mind, not OP's.
  • Syed Irfan Ahmad
    Syed Irfan Ahmad over 2 years
    Changing state to Unchanged only restores values of properties having primitive data types. In my case, an item was added in the collection and changing state to Unchanged didn't restore the collection to its original state ... neither Reload() worked well for the collection property.
  • Syed Irfan Ahmad
    Syed Irfan Ahmad over 2 years
    @Jerther in what scenario the two foreach loops will be executed? I tried by adding and removing an item from my Shipment.ShipmentItems collection but loops didn't get executed (as i was expecting).