Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Concurrency exceptions in Entity Framework

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?

like image 429
Flair Avatar asked Feb 26 '14 08:02

Flair


People also ask

What is a concurrency exception?

Concurrency exceptions (System. Data. DBConcurrencyException) are raised when two users attempt to change the same data in a database at the same time.

Which concurrency approach is not supported in EF core?

Entity Framework Core provides no support for pessimistic concurrency control.

How do you handle optimistic concurrency exceptions?

To resolve optimistic concurrency conflicts, you can take advantage of the Reload method to update the current values in your entity residing in the memory with the recent values in the database. Once reloaded with the updated data, you can attempt to persist your entity again in the database.


2 Answers

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?.

like image 167
Gert Arnold Avatar answered Oct 16 '22 14:10

Gert Arnold


You will get an OptimisticConcurrencyException. Have a look at this.

Now coming to the diffrence.

  • OptimisticConcurrencyException:thrown when an optimistic concurrency violation occurs(suppose more than one perople are changing to the same result,and this will cause the problem of not being sychronized)
  • DbUpdateConcurrencyException:Exception thrown by DbContext when the expected behavior is that SaveChanges for an entity would result in a database update but in fact no rows in the database were affected. This shows that the database has been concurrently updated and a concurrency token that was expected to match did not actually match. State entries referenced by this exception are not serialized due to security and access to the state entries after serialization will return null.
like image 2
Rohan Avatar answered Oct 16 '22 12:10

Rohan