Course contentsShow
← C#
Lesson 1121 of 1,90810. Entity Framework Core ModelingFree lesson

Handling Concurrency Tokens

Use version columns or timestamp-based tokens to manage optimistic concurrency.

Handling Concurrency Tokens

In this lesson, you will learn how to use concurrency tokens to prevent data overwrites in multi-user environments using Optimistic Concurrency.

The Problem: The Lost Update

Imagine two users open the same product record simultaneously. Both see a stock count of 10. User A changes it to 9, and User B changes it to 8. Without protection, the database will simply take the last "Save" command, meaning one update is "lost" forever. Optimistic concurrency assumes conflicts are rare but requires us to verify that the record hasn't changed since we last read it.

Implementing a Version Column

A common approach is to add a [Timestamp] or a byte[] version property to your entity. EF Core treats this property as a "Concurrency Token." When you attempt an update, EF Core includes this token in the WHERE clause of the SQL UPDATE statement.

public class Product
{
    public int Id { get; set; }
    public string Name { get; set; }
    public int Stock { get; set; }

    [Timestamp]
    public byte[] Version { get; set; }
}

When EF Core executes an update, it sends: UPDATE Products SET Stock = 8 WHERE Id = 1 AND Version = @originalVersion;

If another user has already modified the row, the Version in the database will have changed, the WHERE clause will match zero rows, and EF Core will throw a DbUpdateConcurrencyException. This is your cue to catch the exception and decide whether to merge changes, reload the data, or notify the user.

Why use a Token?

By using a dedicated byte[] version column (or a rowversion in SQL Server), you avoid the overhead of checking every single column in the table. You are effectively asking the database, "Update this row only if the state is exactly as it was when I first loaded it." This keeps your application logic clean and your data integrity intact without needing to lock database rows for long periods.

Key Takeaway: Concurrency tokens act as a version identifier that allows EF Core to detect if data has been modified by another process before finalizing an update.