skip to content

SaveChanges & Transactions

What SaveChanges does: one transaction per call, batched statements, explicit transactions and savepoints, retries and interceptors. Interviewers ask why a manual transaction fails under retries.

part ofEntity Framework Coreread it →
on this pageshow

explore

questions

5

In EF Core 10, what does one SaveChangesAsync call do with the pending changes, and what happens when one of its statements fails?

level: juniorimportance: must knowfreq 72%

answer

  1. detect, order, batch, execute
  2. AutoTransactionBehavior.WhenNeeded
  3. returns state entries written
  4. DbUpdateException with Entries
  5. changes not accepted on failure

basics

~20 s

SaveChangesAsync detects changes, turns Added, Modified and Deleted entries into INSERT, UPDATE and DELETE commands, batches them, and runs them atomically. If any statement fails, the transaction rolls back, a DbUpdateException is thrown and the tracked states are kept.

solid answer

~40 s

One `SaveChangesAsync` call runs change detection, orders the commands so that principals are inserted before dependents, groups them into as few round trips as the provider allows, and returns the number of state entries written. By default it is all-or-nothing: with `AutoTransactionBehavior.WhenNeeded` EF Core begins a transaction whenever the save involves more than one command (a single statement is already atomic on its own), commits it on success, and then accepts the changes so the entries become `Unchanged` or `Detached`. If a statement fails, the transaction is rolled back, EF Core throws a `DbUpdateException` (its `Entries` name the entities involved, `InnerException` carries the provider error), and the changes are not accepted - the entries keep their states and generated values are discarded.

code

csharp · 11 lines
csharp
var order = new Order { ShopId = shopId, PlacedAt = now };
foreach (var item in basket)
{
    order.Lines.Add(new OrderLine { PastryId = item.PastryId, Quantity = item.Quantity });
    var stock = await db.StockLevels.SingleAsync(s => s.ShopId == shopId && s.PastryId == item.PastryId);
    stock.OnHand -= item.Quantity;
}
db.Orders.Add(order);

// one call: INSERT order, INSERT lines, UPDATE stock - all or nothing
int written = await db.SaveChangesAsync(cancellationToken);

go deeper

for a junior

Say that nothing is written until SaveChanges, that one call is all-or-nothing by default, and that failures surface as DbUpdateException.

for a middle

Walk through ordering, batching, AutoTransactionBehavior's three values, store-generated keys and what accepting changes does to the entries.

for a senior

Explain what the tracker holds after a failed save, why handlers usually discard the context instead of retrying on it, and which writes bypass SaveChanges.

for a principal

Decide where a team draws one SaveChanges per use case and when work must be split across calls, explicit transactions or messages.

## What SaveChanges is In EF Core, editing objects changes nothing in the database. The **change tracker** records what you added, modified or removed, and `SaveChanges` / `SaveChangesAsync` is the one call that turns those records into SQL. In an ASP.NET Core handler you normally call `SaveChangesAsync` once per request, at the end of the use case. Take a bakery chain's checkout: one call adds an `Order` with three `OrderLine` rows and lowers the `StockLevel` of each pastry it sells. ## What one call does, step by step 1. **Detects changes.** Edits made to tracked entities since the last check are found, so their states are current. 2. **Builds commands.** `Added` entries become `INSERT`s, `Modified` ones become `UPDATE`s of the modified columns, `Deleted` ones become `DELETE`s. 3. **Orders them.** Commands are sorted so that, for example, the `Order` row is inserted before its `OrderLine` rows that reference it. 4. **Batches them.** Several commands share one database round trip; how many go into a batch depends on the provider and its options. 5. **Wraps them in a transaction when needed** (see below) and executes them. 6. **Reads back store-generated values** such as identity keys and fixes up foreign keys in memory. 7. **Accepts the changes** on success: `Added` and `Modified` entries become `Unchanged`, `Deleted` entries become `Detached`. 8. **Returns an `int`**: the number of state entries written to the database. If nothing is pending, it returns `0` without contacting the database. ## The automatic transaction `context.Database.AutoTransactionBehavior` controls whether `SaveChanges` starts its own transaction when none is active: | Value | Behaviour | |---|---| | `WhenNeeded` (default) | begins a transaction whenever the save involves more than one command; a save that is a single command runs without an explicit transaction because the database makes a single statement atomic anyway | | `Always` | always begins one, at the cost of extra round trips | | `Never` | never begins one - a failure part-way can leave earlier commands committed | Either way the guarantee you get by default is the one interviewers expect: one `SaveChanges` call **either fully succeeds or leaves the database unmodified**. If a transaction is already active on the context - one you began, one you passed in, or an ambient `TransactionScope` - `SaveChanges` uses it instead of starting its own. (The older `AutoTransactionsEnabled` boolean is obsolete in favour of `AutoTransactionBehavior`.) ## When a statement fails - The transaction EF Core began is **rolled back**, so none of the order's rows are written. - EF Core throws a **`DbUpdateException`**. Its `Entries` list the `EntityEntry` objects involved, and `InnerException` holds the provider's exception (for Npgsql, a `PostgresException` with the SQL state, such as a unique-violation code). - A conflict detected through a concurrency token surfaces as the derived `DbUpdateConcurrencyException`. - The changes are **not accepted**: the entries keep their `Added`, `Modified` and `Deleted` states, and store-generated values EF Core had read are discarded. Calling `SaveChangesAsync` again resends the same work, which is why most handlers let the exception end the request rather than retry on the same context. ## Things candidates get wrong - Thinking each `Add` or property assignment hits the database immediately. - Thinking each entity gets its own transaction, so a failed `OrderLine` insert leaves an orphan `Order`. - Expecting `SaveChanges` to return the number of rows affected by triggers or cascades; it counts the state entries EF Core wrote. - Calling `SaveChangesAsync` inside a loop, once per entity: that gives up both the atomicity of one call and the batching. - Forgetting that `ExecuteUpdate` / `ExecuteDelete` bypass `SaveChanges` entirely and do not join its transaction.

  • Why might EF Core send a single UPDATE without BEGIN and COMMIT around it?
    With the default `AutoTransactionBehavior.WhenNeeded`, EF Core skips an explicit transaction when the whole save is a single command - one statement is atomic in the database by itself. Set `Database.AutoTransactionBehavior = AutoTransactionBehavior.Always` if you need an explicit transaction regardless, accepting the extra round trips.
  • After a DbUpdateException for a unique-key violation, what is in the change tracker?
    The same pending work: the entries keep their `Added`, `Modified` and `Deleted` states because changes are accepted only on success, and store-generated values are discarded. Calling `SaveChangesAsync` again would resend everything. `ex.Entries` tells you which entities were involved; the provider exception in `InnerException` tells you which constraint failed.

  • Each Add call inserts the row as soon as it is made.
  • SaveChanges returns the number of rows changed by triggers and cascades in the database.
  • If the third statement fails, the first two stay committed by default.
  • A failed SaveChanges marks every entity Unchanged so it is not resent.
  • Calling SaveChangesAsync once per entity in a loop is the safe default.
open as a page

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%

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.

open as a page

With EF Core 10 and EnableRetryOnFailure, why does code inside BeginTransactionAsync throw, and how do you make the whole bakery order retry safely?

level: seniorimportance: must knowfreq 50%

basics

~20 s

A retrying execution strategy replays single operations, so it refuses a transaction you opened: the first query or save inside it throws InvalidOperationException. Wrap the transaction in Database.CreateExecutionStrategy().ExecuteAsync so the whole unit is replayed, rebuilding its state on every attempt.

open as a page

In EF Core 10, how do you make an order placement that writes through two different DbContext types commit or roll back as one transaction?

level: middleimportance: should knowfreq 30%

basics

~20 s

Give both contexts the same DbConnection, begin the transaction on one, and enlist the other with Database.UseTransaction(tx.GetDbTransaction()); then save both and commit once. A TransactionScope also works, but two connections inside it need a distributed transaction.

open as a page

In EF Core 10, how do you stamp CreatedAt and UpdatedAt on every save, and which writes would that stamping miss?

level: seniorimportance: should knowfreq 45%

basics

~20 s

Override SavingChanges and SavingChangesAsync in a SaveChangesInterceptor registered with AddInterceptors, then set CreatedAt on Added entries and UpdatedAt on Modified ones from ChangeTracker.Entries. ExecuteUpdate, ExecuteDelete and raw SQL never pass through SaveChanges, so they are not stamped.

open as a page