Entity Framework - Concurrency

Concurrency Conflicts
A concurrency conflict occurs when one user loads an entity's data in order to edit it, and another user updates the same entity's data before the first user's change is written to the database. If you don't enable the detection of such conflicts, whoever updates the database last overwrites the other user's changes. 

Pessimistic Concurrency (Locking)
If application needs to prevent accidental data loss in concurrency scenarios, one way to do that is to use database locks. This is called pessimistic concurrency. In Pessimistic Concurrency a lock is requested read-only or for update access. If row is locked for update access, no other users are allowed to lock the row either for read-only or update access, because they would get a copy of data that's in the process of being changed. If row is locked for read-only access, other users can also lock it for read-only access but not for update.

Managing locks has disadvantages. It can cause performance problems as the number of users of an application increases. That's why, all database management systems does not support pessimistic concurrency. And Entity Framework provides no built-in support for it.

Optimistic Concurrency
Optimistic concurrency means allowing concurrency conflicts to happen, and then reacting appropriately. In the optimistic concurrency, EF saves the entity to the database, assuming that the same data has not changed since the entity was loaded. If data has changed then an exception will be thrown, we have to resolve conflict before attempting to save it again. Entity Framework supports Optimistic Concurrency by default.

Detecting Concurrency Conflicts
Conflicts can be resolved  by handling OptimisticConcurrencyException exceptions that the Entity Framework throws. We must have to configure database and data modal to detect conflict.

1. In the database table, add a tracking column that can be used to determine when a row has been changed. Configure the Entity Framework to include that column in the Where clause of SQL Update or Delete commands.
2. The data type of the tracking column should be rowversion. The rowversion value is a sequential number that's incremented each time the row is updated. On every update command where clause compare this column. If they don't match, we have a concurrency violation.

By default, the Entity Framework takes the path of “last one in wins,” meaning that the latest update is applied even if someone else updated the data between the time data was retrieved and the time data was saved.

Praesent mattis

Pellentesque viverra vulputate enim. Aliquam erat volutpat. Pellentesque tristique ante ut risus. Quisque dictum. Integer nisl risus, sagittis convallis, rutrum id, elementum congue, nibh. Suspendisse dictum porta lectus. Donec placerat odio vel elit.

Read More