DEV Community

loading...
Cover image for Simple implementation of pessimistic concurrency in Entity Framework

Simple implementation of pessimistic concurrency in Entity Framework

Łukasz Reszke
Open-minded software engineer. Programming mostly in C#. Event Storming facilitator.
・1 min read

An aggregate root can protect invariants by mediating access to internal components. However, it cannot prevent aggregate from reaching an inconsistent state, due to multiple users modifying it. We need to provide a mechanism, which will ensure that other's user's modification does not negatively affect the state of the transaction for other concurrent users.

The good thing is that in Entity Framework we can easily implement the pessimistic concurrency, based on the aggregate's version.

Solution

builder.Property(x => x.Version)
  .HasColumnName("Version")
  .IsConcurrencyToken()
  .HasDefaultValue(0);
Enter fullscreen mode Exit fullscreen mode

The version has to be added to the aggregate. I added it into the base abstract class. Then, before every call of the SaveChanges method, increase the version. The Entity Framework will take care of the correct version being in the database.

If someone modifies the value of the aggregate and hence will increase the version, Entity Framework will throw an exception.

Microsoft.EntityFrameworkCore.DbUpdateConcurrencyException: Database operation expected to affect 1 row(s) but actually affected 0 row(s). Data may have been modified or deleted since entities were loaded.

How do you take care of your aggregate's consistency?

Discussion (0)