How to undo the changes in Entity Framework

In this post i shows you how to implement Undo/Redo feature for DbContext of Entity Framework in C#.

As you all know, the ADO.NET entity framework automatically tracks changes and therefore keeps the original values.

Each entity has an ObjectStateEntry in the ObjectStateManager. The state entry contains original and actual values ​​so that you can use the original value to override the current values, but you must manually do so for each entity.

NorthwindEntities db;
private void frmForm1_Load(object sender, EventArgs e)
{
    db = new NorthwindEntities();
    db.Customers.Load();
    customerBindingSource.DataSource = db.Customers.Local;
}

To fetch data from your database you can put your code in Form_Load event, then load your data to the bindingsource as shown above.

To cancel the change, you can find the entity whose state it UnChanges, then change the state for it.

private void btnCancel_Click(object sender, EventArgs e)
{
    var list = db.ChangeTracker.Entries().Where(x => x.State != EntityState.Unchanged).ToList();
    foreach (var entry in list)
    {
        switch (entry.State)
        {
            case EntityState.Modified:
                entry.CurrentValues.SetValues(entry.OriginalValues);
                entry.State = EntityState.Unchanged;
                break;
            case EntityState.Added:
                entry.State = EntityState.Detached;
                break;
            case EntityState.Deleted:
                entry.State = EntityState.Unchanged;
                break;
        }
    }
    customerBindingSource.ResetBindings(false);
}

You can use the ChangeTracker of DbContext to find dirty items, then set the deleted items state to unchanged and added items to detached. For modified items, use the original values and set the current values of the entry.