SkillPilotAI

Saving, transactions and concurrency

Saving in EF Core runs through the change tracker: SaveChanges only writes what it sees changed, in one transaction. This note covers tracking states, bulk ExecuteUpdate/ExecuteDelete, explicit transactions and optimistic concurrency against lost updates.

55.1 The problem: nothing got saved

  • Goal: change the Steel Bottle (Id 2) price from 399 to 349.
  • The product was loaded with AsNoTracking (handy for reads, from the previous video).
  • SaveChanges returns 0 and the database still has 399.
C#
await using var db = new ShopDb(); var product = await db.Products    .AsNoTracking()    .SingleAsync(p => p.Id == 2); product.Price = 349;var saved = await db.SaveChangesAsync(); Console.WriteLine($"Rows saved: {saved}");
Output
$ dotnet run -- bugExecuted DbCommand (0ms)SELECT "p"."Id", "p"."Name", "p"."Price", ...FROM "Products" AS "p"WHERE "p"."Id" = 2Rows saved: 0DB price: 399.0

55.2 How change tracking works

  • The DbContext's change tracker keeps an original snapshot of every tracked entity.
  • Change a property and the entity moves from Unchanged to Modified.
  • SaveChanges builds SQL only for Added, Modified or Deleted entities.
  • An AsNoTracking entity is Detached: EF never saw the change, so no UPDATE.
StateMeaningSaveChanges sends
DetachedNot in the tracker (AsNoTracking, new object not added)Nothing
UnchangedTracked, same as snapshotNothing
AddedAdded with Add()INSERT
ModifiedA property differs from the snapshotUPDATE of changed columns only
DeletedMarked with Remove()DELETE

55.3 Fix: a tracked query

  • For data you want to update, use a normal (tracked) query.
  • db.Entry(product).State shows Unchanged -> Modified -> Unchanged after save.
  • The UPDATE touches only the Price column. No need to call Update() on a tracked entity.
C#
await using var db = new ShopDb(); var product = await db.Products    .SingleAsync(p => p.Id == 2);Console.WriteLine(db.Entry(product).State); product.Price = 349;Console.WriteLine(db.Entry(product).State); var saved = await db.SaveChangesAsync();Console.WriteLine($"Rows saved: {saved}");Console.WriteLine(db.Entry(product).State);
Output
$ dotnet run -- trackUnchangedModifiedExecuted DbCommand (0ms)UPDATE "Products" SET "Price" = @p0WHERE "Id" = @p1RETURNING 1;Rows saved: 1Unchanged
What SaveChanges does inside
  1. 1.DetectChanges: compare each tracked entity with its snapshot

  2. 2.Build SQL: INSERT, UPDATE, DELETE for changed entities

  3. 3.Run everything in one transaction (all or nothing)

  4. 4.Accept changes: snapshot refreshed, states -> Unchanged

One SaveChanges = one transaction

55.4 ExecuteUpdate and ExecuteDelete

  • Sale: 10% off every Kitchen product. Loading each product and updating one by one is slow.
  • ExecuteUpdateAsync runs one UPDATE straight in the database; ExecuteDeleteAsync runs one DELETE.
  • No SELECT, no SaveChanges needed; they return the affected row count.
C#
var updated = await db.Products    .Where(p => p.Category == "Kitchen")    .ExecuteUpdateAsync(s => s.SetProperty(        p => p.Price, p => p.Price * 0.9m)); var deleted = await db.Products    .Where(p => p.Stock == 0)    .ExecuteDeleteAsync(); Console.WriteLine(    $"Updated: {updated}, Deleted: {deleted}");
Output
$ dotnet run -- bulkUPDATE "Products" AS "p"SET "Price" = ef_multiply("p"."Price", '0.9')WHERE "p"."Category" = 'Kitchen'DELETE FROM "Products" AS "p"WHERE "p"."Stock" = 0Updated: 3, Deleted: 2
  • Catch: they bypass the change tracker. A tracked copy keeps the old value; FindAsync returns it from memory without a query (prints 399.0 after setting 299).
  • After a bulk update use a new DbContext or reload the entity.
C#
var bottle = await db.Products.FindAsync(2); await db.Products    .Where(p => p.Id == 2)    .ExecuteUpdateAsync(s => s.SetProperty(        p => p.Price, 299m)); var again = await db.Products.FindAsync(2);Console.WriteLine(again!.Price);
Output
$ dotnet run -- checkpointSELECT ... FROM "Products" AS "p"WHERE "p"."Id" = @pUPDATE "Products" AS "p"SET "Price" = @pWHERE "p"."Id" = 2399.0

55.5 Explicit transaction: order + stock

  • Inserting the order and reducing stock are separate calls but must succeed or fail together.
  • BeginTransactionAsync opens a transaction; the stock UPDATE only matches when Stock >= qty.
  • rows == 0 -> throw, no commit -> dispose rolls back: 9 bottles gives 0 orders, 2 bottles commits.
C#
await using var tx =    await db.Database.BeginTransactionAsync(); db.Orders.Add(new Order    { ProductId = id, Qty = qty });await db.SaveChangesAsync(); var rows = await db.Products    .Where(p => p.Id == id && p.Stock >= qty)    .ExecuteUpdateAsync(s => s.SetProperty(        p => p.Stock, p => p.Stock - qty)); if (rows == 0)    throw new OutOfStockException();await tx.CommitAsync();
Output
$ dotnet run -- txBegan transaction with isolation level 'Serializable'.INSERT INTO "Orders" ("ProductId", "Qty") ...UPDATE "Products" AS "p"SET "Stock" = "p"."Stock" - @qtyWHERE "p"."Id" = @id AND "p"."Stock" >= @qtyError: Out of stockOrders in DB: 0, Stock: 5Began transaction with isolation level 'Serializable'.INSERT INTO "Orders" ("ProductId", "Qty") ...UPDATE "Products" AS "p" SET "Stock" = ...Committed transaction.Orders in DB: 1, Stock: 3

55.6 The lost update problem

  • Stock is 5. Two DbContexts (warehouse, checkout) load the same product.
  • Warehouse adds 10 and saves; checkout subtracts 1 from its old copy and saves.
  • Expected 14, actual 4: the warehouse update vanished without any error.
C#
await using var warehouse = new ShopDb();await using var checkout = new ShopDb(); var w = await warehouse.Products.FindAsync(2);var c = await checkout.Products.FindAsync(2); w!.Stock += 10;await warehouse.SaveChangesAsync(); c!.Stock -= 1;await checkout.SaveChangesAsync();
Output
$ dotnet run -- lostUPDATE "Products" SET "Stock" = @p0WHERE "Id" = @p1UPDATE "Products" SET "Stock" = @p0WHERE "Id" = @p1Stock now: 4

55.7 Optimistic concurrency: a concurrency token

  • Do not lock the row; at save time check whether someone changed it in between.
  • [ConcurrencyCheck] on a Guid Version makes it a concurrency token. On SQL Server, [Timestamp] + rowversion does this automatically; SQLite has no rowversion.
  • Override SaveChangesAsync to give every Added/Modified product a new Guid.
  • The UPDATE now has WHERE Id = ... AND Version = old; 0 rows -> DbUpdateConcurrencyException.
C#
public class Product{    public int Id { get; set; }    public required string Name { get; set; }    public required string Category { get; set; }    public decimal Price { get; set; }    public int Stock { get; set; }     [ConcurrencyCheck]    public Guid Version { get; set; }} public override Task<int> SaveChangesAsync(    CancellationToken ct = default){    foreach (var e in ChangeTracker        .Entries<Product>())        if (e.State is EntityState.Added            or EntityState.Modified)            e.Entity.Version = Guid.NewGuid();     return base.SaveChangesAsync(ct);}
Output
$ dotnet run -- lostUPDATE "Products" SET "Stock" = @p0, "Version" = @p1WHERE "Id" = @p2 AND "Version" = @p3RETURNING 1;Unhandled exception. Microsoft.EntityFrameworkCore.DbUpdateConcurrencyException: The databaseoperation was expected to affect 1 row(s), butactually affected 0 row(s); data may have beenmodified or deleted since entities were loaded.
Concurrency token stops the lost update
  1. 1.Warehouse and checkout both load stock 5, Version A

  2. 2.Warehouse saves 15: WHERE Version = A matches, Version -> B

  3. 3.Checkout saves 4: WHERE Version = A matches 0 rows

  4. 4.EF throws DbUpdateConcurrencyException

  5. 5.Reload (stock 15, Version B), apply -1, save: 14

Counter: retry. User-edited form: return 409 Conflict

55.8 Handling the conflict

  • For a counter like stock: catch, ReloadAsync to get the fresh stock and Version, then retry.
  • In a Web API where a user edited a form, return 409 Conflict so the user sees fresh data and decides.
C#
for (var attempt = 1; attempt <= 3; attempt++){    try    {        c!.Stock -= 1;        await checkout.SaveChangesAsync();        break;    }    catch (DbUpdateConcurrencyException ex)    {        Console.WriteLine($"Conflict {attempt}");        await ex.Entries.Single().ReloadAsync();    }}Console.WriteLine($"Saved, stock: {c!.Stock}");
Output
$ dotnet run -- retryConflict 1Saved, stock: 14

55.9 Common mistakes

  • SaveChanges inside a loop: 3 round trips, 3 separate commits; a failure midway leaves half an order. Add all, then one SaveChanges.
  • Opening an explicit transaction for every SaveChanges: one SaveChanges already is a transaction; explicit only for several saves.
  • Calling Update() on a tracked entity: not needed.
  • ExecuteUpdate skips your SaveChanges override, so set Version yourself there.
C#
// Wrong: 3 round trips, 3 separate commitsint[] cart = [1, 2, 4];foreach (var id in cart){    db.Orders.Add(new Order        { ProductId = id, Qty = 1 });    await db.SaveChangesAsync();} // Right: 1 SaveChanges = 1 transactionforeach (var id in cart)    db.Orders.Add(new Order        { ProductId = id, Qty = 1 }); await db.SaveChangesAsync();

55.10 Rules for saving

  1. Updates: tracked query. AsNoTracking only for reads.
  2. One request, one SaveChanges.
  3. Bulk work: ExecuteUpdate / ExecuteDelete.
  4. Several saves that are one unit: an explicit transaction.
  5. Shared data: a concurrency token.
  6. In ExecuteUpdate, set Version yourself.

55.11 Interview tips

  • SaveChanges only saves tracked entities, updates only changed columns, and runs in one transaction.
  • ExecuteUpdate / ExecuteDelete: one statement, no loading, but they bypass the change tracker.
  • Concurrency: optimistic, with a token (rowversion on SQL Server, Guid Version on SQLite) checked in the UPDATE's WHERE.
  • 0 rows -> DbUpdateConcurrencyException -> reload, then retry or return 409 Conflict.