Concurrency exceptions in Entity Framework

Flair picture Flair · Feb 26, 2014 · Viewed 19.8k times · Source

When calling SaveChanges / SaveChangesAsync in Entity Framework (CF, C#), if a change conflict occurs (for example, the values has been updated since last read thingy), then which of these two exceptions DbUpdateConcurrencyException OR OptimisticConcurrencyException shall I catch?

And what is the difference between them?

Answer

Gert Arnold picture Gert Arnold · Feb 26, 2014

DbUpdateConcurrencyException is a specific exception thrown by DbContext, so this is the one to catch. This exception may be caused by an underlying OptimisticConcurrencyException, but if so, this exception is wrapped as the inner exception.

Not all update exceptions are caused by concurrency, so you also have to catch DbUpdateException after catching DbUpdateConcurrencyException (because the latter is a subtype of DbUpdateException).

See also Entity framework 5.0 handle optimistic concurrency exception?.