skip to content

In EF Core 10, when do you need Database.BeginTransactionAsync, and how do savepoints behave inside a transaction you began?

level: middleimportance: must knowfreq 55%

answer

  1. several SaveChanges as one unit
  2. await using, then CommitAsync
  3. dispose without commit rolls back
  4. automatic savepoint before each save
  5. CreateSavepointAsync and RollbackToSavepointAsync

basics

~20 s

Use BeginTransactionAsync when several SaveChanges, ExecuteUpdate or raw SQL calls must commit together. Inside it, SaveChanges sets a savepoint before writing and rolls back to it on failure, so the transaction stays usable; named savepoints work by hand too.

solid answer

~40 s

One `SaveChangesAsync` is already atomic, so an explicit transaction is for work that spans more than one call - for example saving an order, reading the generated key, then running an `ExecuteUpdateAsync` that `SaveChanges` would not cover. `await using var tx = await db.Database.BeginTransactionAsync();` starts it; every later `SaveChanges`, query and `ExecuteUpdate` on that context joins it; `await tx.CommitAsync()` makes it durable, and disposing it without a commit rolls it back. Inside a transaction you began, `SaveChanges` does not start its own; it creates a savepoint before writing, rolls back to it if a statement fails and releases it on success, so the outer transaction survives a failed save. `tx.CreateSavepointAsync(name)`, `RollbackToSavepointAsync(name)` and `ReleaseSavepointAsync(name)` give you the same control by hand.

code

csharp · 9 lines
csharp
await using var tx = await db.Database.BeginTransactionAsync(ct);

db.Orders.Add(order);
await db.SaveChangesAsync(ct);          // savepoint __EFSavePoint, then released

db.Invoices.Add(new Invoice { OrderId = order.Id, Total = order.Total });
await db.SaveChangesAsync(ct);          // uses order.Id generated above

await tx.CommitAsync(ct);               // no commit means rollback on dispose

go deeper

for a junior

Know that one SaveChanges is already atomic and that BeginTransactionAsync plus CommitAsync groups several calls.

for a middle

Explain dispose-means-rollback, the automatic savepoint SaveChanges creates inside your transaction, and the manual savepoint methods.

for a senior

Keep transactions short, pair them with ExecuteUpdate deliberately, and reason about tracker state after a savepoint rollback.

for a principal

Decide which use cases justify explicit transactions and how long they may hold locks, versus redesigning into one save per request.

## When one SaveChanges is not enough A single `SaveChanges` call is atomic on its own, so most handlers never touch a transaction API. You need an explicit **database transaction** - a group of statements that commit or roll back together - when one use case needs **more than one round of work** on the same context: - two `SaveChangesAsync` calls, because the second needs a key the first one generated or a check in between; - a mix of tracked saves and **`ExecuteUpdateAsync` / `ExecuteDeleteAsync`**, which run immediately and do not start a transaction themselves; - raw SQL via `Database.ExecuteSqlAsync` that must commit with the tracked changes; - reads that must see the transaction's own uncommitted writes. Which isolation level that transaction runs under is a database topic of its own; the default is the provider's. ## The API ```csharp await using var tx = await db.Database.BeginTransactionAsync(ct); db.Orders.Add(order); await db.SaveChangesAsync(ct); // joins tx await db.LoyaltyAccounts .Where(a => a.CustomerId == order.CustomerId) .ExecuteUpdateAsync(s => s.SetProperty(a => a.Points, a => a.Points + order.Points), ct); await tx.CommitAsync(ct); // both writes become durable ``` - `Database.BeginTransactionAsync()` returns an `IDbContextTransaction`; `Database.CurrentTransaction` exposes it. - **`CommitAsync`** commits; **`RollbackAsync`** discards explicitly. - **Disposing without committing rolls back** - the `await using` makes an exception anywhere in the block undo everything. - `Database.CommitTransactionAsync()` and `RollbackTransactionAsync()` act on the current transaction without holding the variable. ## Savepoints: the automatic one A **savepoint** is a marker inside a transaction that you can roll back to without abandoning the whole transaction. When `SaveChanges` runs while a transaction is already active on the context, it does not begin its own; instead: 1. it creates a savepoint (EF Core names it `__EFSavePoint`) before sending any command; 2. if a statement fails, it rolls back to that savepoint and rethrows; 3. on success it releases the savepoint. The effect: a failed `SaveChanges` leaves your transaction **exactly as it was before the call**, still open and usable. The EF Core docs give the typical reason - correcting a problem, such as an optimistic concurrency conflict, and calling `SaveChanges` again inside the same transaction. The behaviour is on by default and controlled by `Database.AutoSavepointsEnabled`. Two limits: - On SQL Server, EF Core does not create savepoints when **MARS** (Multiple Active Result Sets) is enabled on the connection, so a failed save there can leave the transaction in an unknown state. - A provider whose transactions do not support savepoints throws `NotSupportedException` from the savepoint methods; relational providers such as Npgsql support them. ## Savepoints by hand | Call on `IDbContextTransaction` | Effect | |---|---| | `CreateSavepointAsync("name")` | marks the current point | | `RollbackToSavepointAsync("name")` | undoes everything after the mark, keeps the transaction open | | `ReleaseSavepointAsync("name")` | discards the mark; the work stays in the transaction | A bakery's nightly ordering job can write each branch's order and its stock adjustment inside one transaction, and roll back only the branch whose work failed. The automatic savepoint covers a single `SaveChanges`; a manual one covers a group of calls: ```csharp await tx.CreateSavepointAsync("BeforeBranch", ct); try { await db.SaveChangesAsync(ct); await db.StockLevels.Where(s => s.ShopId == branchId) .ExecuteUpdateAsync(s => s.SetProperty(x => x.Reserved, 0), ct); } catch (Exception ex) when (ex is DbUpdateException or DbException) { await tx.RollbackToSavepointAsync("BeforeBranch", ct); db.ChangeTracker.Clear(); // drop the entries that failed } ``` Rolling back the database does not touch the change tracker: entries from the failed save are still pending until you clear or fix them. ## Pitfalls - Beginning a transaction and forgetting `CommitAsync`: disposal silently rolls back, and the handler returns success. - Holding a transaction open across a slow outgoing HTTP call, keeping locks for its whole duration. - Mixing an explicit transaction with `EnableRetryOnFailure` without wrapping it in the execution strategy - that combination throws.

  • Inside a transaction you began, the second SaveChangesAsync throws. Is the first save's work lost?
    No. Because a transaction was active, `SaveChanges` created a savepoint before writing and rolled back only to it, so the first save's work is still in the open transaction. You can fix the problem and save again, roll back, or commit what is there.
  • Does RollbackToSavepointAsync also undo the changes in the DbContext?
    No. It undoes database work after the savepoint; the change tracker still holds whatever entries it held. Either fix and resave them, or call `ChangeTracker.Clear()` (or use a new context) so the failed changes are not sent again.

  • Every SaveChanges inside my transaction commits on its own.
  • Disposing a transaction without CommitAsync commits it automatically.
  • A failed SaveChanges inside my transaction always dooms the whole transaction.
  • RollbackToSavepointAsync also resets the change tracker's entries.
  • ExecuteUpdateAsync joins SaveChanges' own transaction, so no explicit transaction is needed.