Entity Framework Concurrency Discover Implement Optimistic Concurrency
The situations in which multiple processes or users access or change the same data in a database at the same time.
Concurrency Control
To implement optimistic concurrency control, you need to configure properties as concurrency tokens. So whenever an update or delete operation is performed during SaveChanges, the value of the concurrency token on the database is compared against the original value.
- The operation is completed successfully if the values match.
- If the values do not match, Entity Framework assumes that another user has performed a conflicting operation and aborts the current transaction.
- It is the responsibility of database providers to compare the concurrency token values.
Concurrency Conflict
A concurrency conflict occurs when one user changes the data, and then another user updates the same data before the first user's change is written to the database. You can use the following two approaches to detect concurrency conflict.
- Configuring existing properties as concurrency tokens
- Adding a new "rowversion" property to act as a concurrency token.
Configure Existing Property
The simplest way to configure existing properties is by using the data annotations ConcurrencyCheck
attribute.
public class Book { public int BookId { get; set; } [ConcurrencyCheck] public string Title { get; set; } }
The ConcurrencyCheck
attribute specifies that a property should be included in a WHERE
clause in an UPDATE
or DELETE
statement as part of concurrency management.
You can also use the Fluent API IsConcurrencyToken() method to configure the existing properties.
protected override void OnModelCreating(ModelBuilder modelBuilder) { modelBuilder.Entity<Book>() .Property(b => b.Title).IsConcurrencyToken(); }
Add RowVersion Property
A RowVersion
is a property where a new value is generated by the database every time a row is inserted or updated and it is also treated as a concurrency token.
- The
Timestamp
attribute is used to create a column with timestamp data type in the SQL Server database. - EF Code first will treat Timestamp properties the same as
ConcurrencyCheck
properties.
public class Book { public int BookId { get; set; } public string Title { get; set; } [Timestamp] public byte[] RowVersion { get; set; } }
ZZZ Projects