Concurrency tokens and transactions
Concurrency tokens and transactions
Optimistic concurrency assumes that conflicts are uncommon but detects them before an update silently overwrites another writer. A concurrency token is compared against its originally read value during an update or delete. Transactions group database operations into one commit or rollback.
For SQLite use an application-managed revision or GUID token; SQL Server rowversion is a different provider-specific feature. All relevant writers must update the token when modifying protected data. EF uses the original token in its predicate and raises DbUpdateConcurrencyException when the expected row is not affected. Handle conflicts by reloading values and choosing a business merge, rejection or bounded retry. Never blindly overwrite the newer data. A retry of a transaction must be an idempotent or otherwise safely repeatable unit; avoid repeating irreversible external effects. Relational providers normally make one SaveChanges atomic. An explicit transaction is needed for a unit spanning multiple saves; commit only after all steps succeed. Savepoints permit partial rollback inside an active transaction when supported. After rollback, tracked objects may still contain changes: use a fresh context or reconcile state. Database locks, transaction isolation and concurrency tokens solve different problems. ExecuteUpdate and ExecuteDelete bypass tracked SaveChanges and its automatic concurrency-token checks. For a guarded set-based write, include the expected revision and domain preconditions in the query, change the revision in the same statement, and inspect affected rows. These operations do not synchronize previously tracked objects or automatically group multiple calls into one transaction. All examples run sequentially on one open in-memory connection, not a real simultaneous multi-connection load.
Baseline: .NET 10 / C# 14, Microsoft.EntityFrameworkCore.Sqlite 10.0.15 (published package, restore and advisory checks pending). Each independent project includes its own complete source and project file. In an approved environment with a reviewed SDK and packages, restore from approved sources, then run dotnet build --no-restore and dotnet run --no-build in the fixture directory. Except for the migration-operation inspection, each uses its own open SQLite in-memory connection, synthetic catalog and schema created by EnsureCreated. No external database, account or credential is required. Expected results are reasoned, not executed.
Reject a stale update from another context
Both contexts read revision 1. The first writer explicitly advances the token; the second tries to save an old revision.
using Microsoft.Data.Sqlite;using Microsoft.EntityFrameworkCore;using var connection = new SqliteConnection("Data Source=:memory:;Foreign Keys=True");connection.Open();var options = new DbContextOptionsBuilder<Catalog>().UseSqlite(connection).Options;using var db = new Catalog(options);db.Database.EnsureCreated();db.Categories.Add(new Category { Id = 1, Name = "Science" });db.Books.AddRange(new Book { Id = 1, Title = "Atlas", Stock = 4, CategoryId = 1 }, new Book { Id = 2, Title = "Comet", Stock = 0, CategoryId = 1 });db.SaveChanges();db.ChangeTracker.Clear();using var other = new Catalog(options);var first = db.Books.Single(b => b.Id == 1);var stale = other.Books.Single(b => b.Id == 1);first.Stock = 6;first.Revision++;db.SaveChanges();stale.Stock = 9;stale.Revision++;try { other.SaveChanges(); }catch (DbUpdateConcurrencyException) { Console.WriteLine("conflict"); }using var verify = new Catalog(options);Console.WriteLine(verify.Books.Single(b => b.Id == 1).Stock);class Book { public int Id { get; set; } public string Title { get; set; } = ""; public int Stock { get; set; } public int Revision { get; set; } = 1; public int CategoryId { get; set; } public Category? Category { get; set; }}class Category { public int Id { get; set; } public string Name { get; set; } = ""; public List<Book> Books { get; } = new();}class Catalog(DbContextOptions<Catalog> options) : DbContext(options) { public DbSet<Book> Books => Set<Book>(); public DbSet<Category> Categories => Set<Category>(); protected override void OnModelCreating(ModelBuilder model) { model.Entity<Book>().HasKey(b => b.Id); model.Entity<Book>().Property(b => b.Title).IsRequired(); model.Entity<Book>().Property(b => b.Revision).IsConcurrencyToken(); model.Entity<Book>().HasIndex(b => b.Title).IsUnique(); model.Entity<Book>().HasOne(b => b.Category).WithMany(c => c.Books) .HasForeignKey(b => b.CategoryId).OnDelete(DeleteBehavior.Restrict); }}Expected output (not executed):
conflict6The stale original token no longer matches. The accepted update remains intact.
Rollback two saves as a unit
Transfer one unit between the two sample books, then simulate cancellation of the business operation before commit.
using Microsoft.Data.Sqlite;using Microsoft.EntityFrameworkCore;using var connection = new SqliteConnection("Data Source=:memory:;Foreign Keys=True");connection.Open();var options = new DbContextOptionsBuilder<Catalog>().UseSqlite(connection).Options;using var db = new Catalog(options);db.Database.EnsureCreated();db.Categories.Add(new Category { Id = 1, Name = "Science" });db.Books.AddRange(new Book { Id = 1, Title = "Atlas", Stock = 4, CategoryId = 1 }, new Book { Id = 2, Title = "Comet", Stock = 0, CategoryId = 1 });db.SaveChanges();db.ChangeTracker.Clear();using (var tx = db.Database.BeginTransaction()) { var from = db.Books.Single(b => b.Id == 1); from.Stock--; from.Revision++; db.SaveChanges(); var to = db.Books.Single(b => b.Id == 2); to.Stock++; to.Revision++; db.SaveChanges(); tx.Rollback();}using var verify = new Catalog(options);foreach (var book in verify.Books.OrderBy(b => b.Id)) Console.WriteLine(book.Stock);class Book { public int Id { get; set; } public string Title { get; set; } = ""; public int Stock { get; set; } public int Revision { get; set; } = 1; public int CategoryId { get; set; } public Category? Category { get; set; }}class Category { public int Id { get; set; } public string Name { get; set; } = ""; public List<Book> Books { get; } = new();}class Catalog(DbContextOptions<Catalog> options) : DbContext(options) { public DbSet<Book> Books => Set<Book>(); public DbSet<Category> Categories => Set<Category>(); protected override void OnModelCreating(ModelBuilder model) { model.Entity<Book>().HasKey(b => b.Id); model.Entity<Book>().Property(b => b.Title).IsRequired(); model.Entity<Book>().Property(b => b.Revision).IsConcurrencyToken(); model.Entity<Book>().HasIndex(b => b.Title).IsUnique(); model.Entity<Book>().HasOne(b => b.Category).WithMany(c => c.Books) .HasForeignKey(b => b.CategoryId).OnDelete(DeleteBehavior.Restrict); }}Expected output (not executed):
40The database rolls both updates back, even though SaveChanges returned successfully inside the transaction.
Keep an earlier change using a savepoint
Save one change, mark a savepoint, save another, then roll back only the later change.
using Microsoft.Data.Sqlite;using Microsoft.EntityFrameworkCore;using var connection = new SqliteConnection("Data Source=:memory:;Foreign Keys=True");connection.Open();var options = new DbContextOptionsBuilder<Catalog>().UseSqlite(connection).Options;using var db = new Catalog(options);db.Database.EnsureCreated();db.Categories.Add(new Category { Id = 1, Name = "Science" });db.Books.AddRange(new Book { Id = 1, Title = "Atlas", Stock = 4, CategoryId = 1 }, new Book { Id = 2, Title = "Comet", Stock = 0, CategoryId = 1 });db.SaveChanges();db.ChangeTracker.Clear();using (var tx = db.Database.BeginTransaction()) { var a = db.Books.Single(b => b.Id == 1); a.Stock = 5; a.Revision++; db.SaveChanges(); tx.CreateSavepoint("before_second"); var b = db.Books.Single(b => b.Id == 2); b.Stock = 8; b.Revision++; db.SaveChanges(); tx.RollbackToSavepoint("before_second"); tx.Commit();}using var verify = new Catalog(options);foreach (var book in verify.Books.OrderBy(b => b.Id)) Console.WriteLine(book.Stock);class Book { public int Id { get; set; } public string Title { get; set; } = ""; public int Stock { get; set; } public int Revision { get; set; } = 1; public int CategoryId { get; set; } public Category? Category { get; set; }}class Category { public int Id { get; set; } public string Name { get; set; } = ""; public List<Book> Books { get; } = new();}class Catalog(DbContextOptions<Catalog> options) : DbContext(options) { public DbSet<Book> Books => Set<Book>(); public DbSet<Category> Categories => Set<Category>(); protected override void OnModelCreating(ModelBuilder model) { model.Entity<Book>().HasKey(b => b.Id); model.Entity<Book>().Property(b => b.Title).IsRequired(); model.Entity<Book>().Property(b => b.Revision).IsConcurrencyToken(); model.Entity<Book>().HasIndex(b => b.Title).IsUnique(); model.Entity<Book>().HasOne(b => b.Category).WithMany(c => c.Books) .HasForeignKey(b => b.CategoryId).OnDelete(DeleteBehavior.Restrict); }}Expected output (not executed):
50The first change commits while the second is undone. This depends on provider savepoint support; the original tracker is not a reliable post-rollback read.
Apply the concept
Two staff members edit the same stock record. Specify a revision policy, conflict response and transaction boundary for a transfer, including what happens if a notification fails.
Use the manual practice and knowledge check to reason about the boundary. Do not apply these examples to a production database.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Concurrency tokens and transactions — knowledge check
Apply the lesson concepts to the following scenarios.
Which value is compared during an optimistic update?
What exception represents an unexpected affected-row count?
Does SQLite offer SQL Server rowversion semantics?
What does rolling back the current database transaction undo?
Why bound and design retries carefully?