18

When handling several potential exceptions during a context.SaveChanges() one of the exceptions is OptimisticConcurrency. Microsoft's documentation on this at http://msdn.microsoft.com/en-us/library/bb399228.aspx discusses this for EF 4.x ...

try
{
    // Try to save changes, which may cause a conflict.
    int num = context.SaveChanges();
    Console.WriteLine("No conflicts. " +
        num.ToString() + " updates saved.");
}
catch (OptimisticConcurrencyException)
{
    // Resolve the concurrency conflict by refreshing the 
    // object context before re-saving changes. 
    context.Refresh(RefreshMode.ClientWins, orders);

    // Save changes.
    context.SaveChanges();
    Console.WriteLine("OptimisticConcurrencyException "
    + "handled and changes saved");
}

... but on EF 5.0 (RC), this doesn't seem to work because Refresh() doesn't exist on my EF5, code-first, DbContext derived context class.

I do see context.Entry(context.SalesOrderHeaders).Reload(); - but that appears to be a straightup reload-from-db and not a refresh/merge (with policy client wins).

Any ideas how to handle Optimistic concurrency exceptions in EF5? Actually even general pointers on exception handling in SaveChanges() would be nice

Thanks

DeepSpace101
  • 13,110
  • 9
  • 77
  • 127

2 Answers2

31

The way how to solve concurrency exception in DbContext API reloads original entity:

catch (DbUpdateConcurrencyException ex)
{
    // Get failed entry
    var entry = ex.Entries.Single(...);
    // Overwrite original values with values from database but don't
    // touch current values where changes are held
    entry.OriginalValues.SetValues(entry.GetDatabaseValues());
}

You should also be able to use the mentioned code but you must get ObjectContext instance from your DbContext instance (it is just a wrapper around ObjectContext).

catch (DbUpdateConcurrencyException ex)
{
    var objContext = ((IObjectContextAdapter)context).ObjectContext;
    // Get failed entry
    var entry = ex.Entries.Single(...);
    // Now call refresh on ObjectContext
    objContext.Refresh(RefreshMode.ClientWins, entry.Entity);        
}

You may even try:

objContext.Refresh(RefreshMode.ClientWins, ex.Entries.Select(e => e.Entity));
Ladislav Mrnka
  • 360,892
  • 59
  • 660
  • 670
  • 2
    When trying to understand `Single(...)` in your DbContext API example, I though of iterating over all failures via `catch (DbUpdateConcurrencyException ex){foreach (var entry in ex.Entries){entry.OriginalValues.SetValues(entry.GetDatabaseValues());}` What do you think? Also, the `don't touch current values where changes are held` isn't very clear to me :( .. seems both will fetch dB values? – DeepSpace101 Aug 02 '12 at 16:58
  • 1
    Each entry contains current values and original values - server wins strategy overwrites both sets but client wins overwrites only original set. – Ladislav Mrnka Aug 02 '12 at 17:00
  • 1
    @DeepSpace101 A bit late to the party here, but the [documentation](https://msdn.microsoft.com/en-us/data/jj592904.aspx) for EF 6.x specifically states that Entries will always hold exactly 1 entity for DbUpdateConcurrencyException (last paragraph of Resolving optimistic concurrency exceptions with Reload) – Søren Boisen Mar 04 '16 at 10:56
  • Additional information: The element at index 0 in the collection of objects to refresh is in the added state. Objects in this state cannot be refreshed , the problem is concurrency exception appear after insert – haitham sha Jul 15 '16 at 21:44
1

If your changes are only against the one entity (particular one row, not others tables etc), which is covered by the concurrency mechanism you are allowed to refresh context by disposing the old one and create new one. The thing is when the context is disposed every changed entities and not yet committed are detached from the context and the changes are lost. So be careful about the scope of your unit work!

    catch (DbUpdateConcurrencyException)
    {
        context.Dispose();
        context = new DBContext();
        Entity entity = context.Set<Entity>().Find(entityFromOldContext.Id);

        entity.Property1 = entityFromOldContext.Property1;
        entity.Property2 += 4;

        context.commit();
    }

In the Entity I use extra property for controlling concurrency as follows:

[Timestamp]
public Byte[] RowVersion { get; set; }

It is maybe not elegant way (and breaks UnitOfWork pattern), but it might be useful in some situations and finally an alternative to the above posts.

Bronek
  • 10,722
  • 2
  • 45
  • 46