Skip to content
Tutorials Center
My learning

Topics

Lesson 28 of 41 ยท Change Tracking and Saving

SaveChanges and Transactions

Understand how EF Core SaveChanges works as an atomic unit, command ordering, batching, explicit transactions, savepoints, retries with execution strategies and TransactionScope, with runnable stand-ins.

SaveChanges is where everything you did to tracked entities becomes SQL. It looks like a single call, but it does a lot: it finds changes, orders commands so foreign keys stay valid, batches statements, wraps them in a transaction, reads back generated values and resets the tracker. Understanding it prevents half-saved data and explains puzzling errors.

The EF Core code is read-only here. Runnable blocks are plain-C# stand-ins for the transaction behavior.

SaveChanges is a transaction

By default, one SaveChanges call runs all its commands in one database transaction. Either every insert, update and delete succeeds or none does:

C#
db.Orders.Add(new Order { CustomerId = 5, Total = 80m });
db.Products.Find(1)!.Stock -= 2;
db.Audits.Add(new Audit { Message = "Order placed" });

await db.SaveChangesAsync();   // all three changes commit together, or roll back together

If the third command fails (a constraint violation, a deadlock), the first two are rolled back, and the entities in the tracker stay in their pre-save states so you can fix the problem and retry. That atomicity is the reason to do related changes with one SaveChanges rather than several.

What happens inside

  1. DetectChanges finds modified entities.
  2. Commands are sorted by dependency: principals inserted before dependents, dependents deleted before principals.
  3. Commands are batched: many INSERTs go out in one round trip (SQL Server and others support batching; the default batch size is provider-specific).
  4. The transaction is committed.
  5. Generated values (identity keys, defaults, row versions) are read back and written to your entities.
  6. The tracker accepts the changes: everything becomes Unchanged.
flowchart LR
    A["DetectChanges"] --> B["Order commands by foreign keys"]
    B --> C["Batch statements"]
    C --> D["BEGIN / execute / COMMIT"]
    D --> E["Read back generated values"]
    E --> F["Accept changes: Unchanged"]
    D -. error .-> G["ROLLBACK, entities keep their state"]

Any failure at the database step rolls back the whole batch.

The stand-in below mimics "all or nothing" using a snapshot of a bank-like table: apply commands, and if one fails, restore the copy.

C# Stand-in: all-or-nothing saving

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

Generated keys and the order of work

You can build a whole graph and save once. EF Core inserts the blog first, learns its new Id, and writes it into each post's BlogId. For a key generated by the database, reading blog.Id before saving gives a temporary value (negative or zero); after saving it is the real key.

If you need the key in the middle of your own logic, SaveChanges earlier, or let EF Core generate keys on the client side (a Guid, or a HiLo sequence).

Explicit transactions

Sometimes one unit of work needs more than one SaveChanges (for instance, you need a generated key before the next step) or mixes EF Core with raw SQL. Then open a transaction yourself:

C#
await using var tx = await db.Database.BeginTransactionAsync();
try
{
    var order = new Order { CustomerId = 5 };
    db.Orders.Add(order);
    await db.SaveChangesAsync();                 // order.Id is now known

    await db.Database.ExecuteSqlInterpolatedAsync(
        $"UPDATE Stock SET Qty = Qty - {qty} WHERE ProductId = {productId}");

    db.OrderLines.Add(new OrderLine { OrderId = order.Id, ProductId = productId, Qty = qty });
    await db.SaveChangesAsync();

    await tx.CommitAsync();
}
catch
{
    // disposing the transaction without Commit rolls it back; just rethrow
    throw;
}

Disposing an uncommitted transaction rolls it back, so the await using is the safety net.

Savepoints

Inside a transaction you can create a savepoint and undo only part of the work. EF Core uses savepoints automatically when SaveChanges runs inside an existing transaction, so a failing SaveChanges only undoes its own part. You can also manage them by hand:

C#
await tx.CreateSavepointAsync("BeforeRisky");
// ... risky changes and SaveChanges ...
await tx.RollbackToSavepointAsync("BeforeRisky");     // keep the rest of the transaction

Sharing a transaction

Two contexts can join the same transaction through the shared connection: db2.Database.UseTransaction(tx.GetDbTransaction()). Ambient TransactionScope also works with most providers, but explicit transactions are clearer, and a scope that spans several connections can escalate to a distributed transaction, which is not supported everywhere.

C# Stand-in: transaction with a savepoint

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

Retries and execution strategies

Cloud databases drop connections briefly. Providers offer an execution strategy that retries failed operations:

C#
options.UseSqlServer(cs, o => o.EnableRetryOnFailure(maxRetryCount: 5));

A retrying strategy cannot retry a transaction you opened by hand (it does not know which part to redo), so wrap your whole unit of work in the strategy:

C#
var strategy = db.Database.CreateExecutionStrategy();
await strategy.ExecuteAsync(async () =>
{
    await using var tx = await db.Database.BeginTransactionAsync();
    // ... the whole unit of work ...
    await tx.CommitAsync();
});

Timestamps and auditing with overrides

Because everything flows through one method, you can override it:

C#
public override Task<int> SaveChangesAsync(CancellationToken ct = default)
{
    foreach (var entry in ChangeTracker.Entries<IAuditable>())
    {
        if (entry.State == EntityState.Added)    entry.Entity.CreatedAt = DateTime.UtcNow;
        if (entry.State == EntityState.Modified) entry.Entity.UpdatedAt = DateTime.UtcNow;
    }
    return base.SaveChangesAsync(ct);
}

Interceptors are a cleaner place for this.

Common mistakes

  • Calling SaveChanges in a loop for each entity: one transaction and round trip per call. Add everything, save once.
  • Doing slow work inside a transaction (HTTP calls, waiting for users): it holds locks and blocks others.
  • Forgetting the tracker after a failure. Entities stay Added or Modified; retrying with the same context may repeat the error. Often it is best to discard the context and start over.
  • Mixing two contexts without a shared transaction, then being surprised that one change committed and the other did not.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does a single SaveChanges call guarantee by default?

    SaveChanges wraps its commands in one transaction, so it is atomic.
  2. 2. When do you need an explicit transaction?

    Explicit transactions group multiple operations beyond a single SaveChanges.
  3. 3. What happens if you dispose a transaction without calling Commit?

    An uncommitted transaction rolls back on dispose.
  4. 4. Why does EF Core sort commands before sending them?

    Inserting a dependent before its principal would violate the foreign key.

Summary

  • One SaveChanges is atomic: detect changes, sort and batch commands, commit, read back generated values.
  • Prefer a single SaveChanges for related changes; use BeginTransaction when you truly need several steps.
  • Savepoints undo part of a transaction; execution strategies retry transient failures around a whole unit of work.
  • Override SaveChanges (or use interceptors) for audit timestamps.

Next: Add, update, remove and disconnected entities