EF Core IsConcurrencyToken

The IsConcurrencyToken method is used to specify that a property should be included in a WHERE clause in an UPDATE or DELETE statement as part of concurrency management.

language-csharp
|
public class SampleContext : DbContext
{
    public DbSet<Author> Authors { get; set; }
    
    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        modelBuilder.Entity<Author>()
            .Property(a => a.FirstName).IsConcurrencyToken()
         modelBuilder.Entity<Author>()
            .Property(a => a.LastName).IsConcurrencyToken();
    } 
}

public class Author
{
    public int AuthorId { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public string Biography { get; set; }
    public ICollection<Book> Books { get; set; }
}

When applied to a byte array property in combination with the ValueGeneratedOnAddOrUpdate method, the IsConcurrencyToken method denotes that the property should map to a database type that provides automatic row-versioning, such as the SQL Server rowversion type:

language-csharp
|
public class SampleContext : DbContext
{
    public DbSet<Author> Authors { get; set; }
    
    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        modelBuilder.Entity<Author>()
            .Property(a => a.RowVersion)
            .IsConcurrencyToken()
            .ValueGeneratedOnAddOrUpdate();
    } 
}

public class Author
{
    public int AuthorId { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public string Biography { get; set; }
    public ICollection<Book> Books { get; set; }
    public byte[] RowVersion { get; set; }
}

Data Annotations

The Data Annotations equivalents are the IsConcurrencyToken method is the ConcurrencyCheck attribute and the Timestamp attribute.

Further Reading


Date Modified: 2023-02-27
Author:

Edit this page in GitHub

Got any EF Core Question?