Covers the SaveChanges pipeline in EF Core 10: automatic DetectChanges with snapshot tracking, dependency ordering of commands, SQL Server batching and MaxBatchSize, AutoTransactionBehavior, OUTPUT clauses for generated values, temporary keys and relationship fix-up, and what happens on failure.
SaveChanges runs a pipeline:
DetectChanges: compares every tracked entity with its original-values snapshot and marks changed properties Modified (skipped if AutoDetectChangesEnabled is false, so you must call it yourself).MaxBatchSize is 42).INSERT ... OUTPUT INSERTED.[Id] returns identity keys and UPDATE ... OUTPUT INSERTED.[RowVersion] returns new row versions; EF Core replaces temporary keys, propagates them to foreign keys, then marks everything Unchanged.The trade-off: one call gives atomicity and few round trips, but its cost grows with every tracked entity.
"
SaveChangesis a small unit-of-work engine. First it callsDetectChanges. With the default snapshot tracking, EF Core kept a copy of each entity's values when it was loaded, so it walks every tracked entry, compares current values with that snapshot and flags changed properties. That's why my UPDATE only contains the columns I actually changed, and also whySaveChangesgets slower when the context tracks tens of thousands of entities: that scan is proportional to everything tracked, not just what changed.Then it builds one modification command per Added, Modified or Deleted entity and sorts them topologically by the relationships. If I add a new order with three lines and the order key is an identity column, the order INSERT has to run first so the lines can get its generated id; with client-generated keys such as
Guid.CreateVersion7()the key is known up front, but EF Core still inserts principals first to satisfy the foreign key constraints. For deletes it's the reverse. The commands are then batched, so on SQL Server several INSERTs or UPDATEs go in one round trip, up to 42 statements by default, which I can change withMaxBatchSize. If there's more than one statement, EF Core opens a transaction for me, so the whole save is atomic. If I've already started a transaction, or there's an ambientTransactionScope, it uses that instead.Finally, generated values come back through an
OUTPUTclause: identity keys from the INSERTs, new row versions from the UPDATEs, plus any database defaults. EF Core replaces the temporary keys it used for Added entities, copies them into the dependants' foreign keys, wires up navigations, and accepts the changes, so Added and Modified become Unchanged and Deleted becomes Detached. If anything fails, nothing is accepted and the transaction rolls back. The mistake I see is callingSaveChangesinside a loop, once per row: that throws away batching and the single transaction, and turns one round trip into thousands."
| Step | What happens | Knob |
|---|---|---|
| Detect | Snapshot comparison of all tracked entities | ChangeTracker.AutoDetectChangesEnabled |
| Validate | Required properties, key conflicts, orphan handling | CascadeDeleteTiming, DeleteOrphansTiming |
| Order | Topological sort on foreign keys | Model relationships |
| Batch | Group commands into round trips | UseSqlServer(o => o.MaxBatchSize(n)) |
| Transact | Implicit transaction if more than one statement | Database.AutoTransactionBehavior |
| Execute | Send SQL, read OUTPUT values |
HasTrigger for tables with triggers |
| Accept | States reset, keys fixed up, events raised | SaveChanges(acceptAllChangesOnSuccess: false) |
| Value | Meaning |
|---|---|
WhenNeeded (default) |
Transaction only when the save needs more than one statement |
Always |
Always wrap, even a single statement |
Never |
Never wrap; you own atomicity (rarely right) |
SaveChanges only knows what the tracker tells it. An entity rebuilt from a request has no snapshot, so DetectChanges cannot find its changes; it is saved only if you Attach/Update it or mark properties modified, and Update() makes every column part of the UPDATE.
A nightly job inserted [20,000] rows with SaveChanges inside the loop and took [~9 minutes], one round trip and one transaction per row. Moving to one SaveChanges per [1,000] rows with ChangeTracker.Clear() between chunks took it to [~25 seconds], because each chunk was sent in about 24 batched round trips inside a single transaction.
Checks whether the candidate understands what happens inside SaveChanges: change detection, ordering, batching, transactions and key fix-up.
Green flags
SaveChanges is atomic on its own and when it opens a transaction.OUTPUT.Red flags
SaveChanges per row by habit.load/attach -> copy property values into snapshot
your code -> mutates the entity
DetectChanges-> for each tracked entry:
for each property: current != original ? mark modified
The default strategy is ChangeTrackingStrategy.Snapshot. Entities can implement INotifyPropertyChanged (and INotifyPropertyChanging) and the model can opt into ChangedNotifications or ChangingAndChangedNotifications, so EF Core is told about changes instead of scanning. Few teams do this: it adds boilerplate to every entity, and short-lived contexts make the scan cheap.
Added: Customer(temp key) <- Order(temp key) <- OrderLine x3
Sorted: INSERT Customer -> INSERT Order -> INSERT OrderLines
Deleted: DELETE OrderLines -> DELETE Order
EF Core builds a graph of commands and sorts it. Cycles (for example two entities pointing at each other with required keys) cannot be ordered and throw; you break them with an optional foreign key and two saves.
Inserts into a table with an identity key use INSERT ... OUTPUT INSERTED.[Id] per row or a MERGE for larger groups; updates and deletes are concatenated. One batch is one DbCommand.
SET NOCOUNT ON;
INSERT INTO [Orders] ([CustomerId], [PlacedAt], [Status])
OUTPUT INSERTED.[Id]
VALUES (@p0, @p1, @p2);
UPDATE [Customers] SET [LastOrderAt] = @p3
OUTPUT 1
WHERE [Id] = @p4;
SQL Server allows 2,100 parameters per command, so very wide entities produce smaller batches. The default MaxBatchSize is 42, chosen from benchmarks; bigger is not always faster.
SQL Server rejects OUTPUT without INTO on a table that has an enabled trigger. Declare it with builder.ToTable(t => t.HasTrigger("trg_Audit")) (EF Core 8 and later) so EF Core falls back to a slower but compatible pattern.
An Added entity with a store-generated key gets a temporary value so the identity map and relationships work before the row exists. After the INSERT, EF Core swaps in the real key, updates every dependant's foreign key and navigation, and refreshes the identity map. Entry(e).Property(p).IsTemporary tells you whether a key is still temporary.
If a command fails, the exception (DbUpdateException, DbUpdateConcurrencyException) surfaces, the implicit transaction rolls back, and no changes are accepted. Entities stay Added/Modified/Deleted, so a retry resends the same work. SaveChanges(acceptAllChangesOnSuccess: false) plus AcceptAllChanges() lets you defer acceptance until an outer operation succeeds.
SavingChanges, SavedChanges and SaveChangesFailed events, and ISaveChangesInterceptor, run around this pipeline. That is where audit columns and soft delete are usually implemented.
LogTo(Console.WriteLine, LogLevel.Information); count the commands, then set MaxBatchSize(10) and count again.db.Entry(order).Property(o => o.Id).IsTemporary before and after saving.HasTrigger.SaveChanges per row vs per 1,000 rows using BenchmarkDotNet or a Stopwatch.AutoTransactionBehavior.Never in a test and make the third statement fail to see a partial save.Configuring and observing the SaveChanges pipeline.
// Program.cs
builder.Services.AddDbContext<ShopDbContext>(o => o
.UseSqlServer(builder.Configuration.GetConnectionString("Shop"),
sql => sql.MaxBatchSize(100)) // measure before changing the default of 42
.LogTo(Console.WriteLine, LogLevel.Information));
namespace Shop.Orders;
using Microsoft.EntityFrameworkCore;
public sealed class PlaceOrderHandler(ShopDbContext db)
{
public async Task<int> HandleAsync(int customerId, IReadOnlyList<(int ProductId, int Qty)> items, CancellationToken ct)
{
var customer = await db.Customers.SingleAsync(c => c.Id == customerId, ct);
var order = new Order { Customer = customer, PlacedAt = DateTimeOffset.UtcNow };
foreach (var (productId, qty) in items)
order.Lines.Add(new OrderLine { ProductId = productId, Quantity = qty });
db.Orders.Add(order); // order + lines Added, temporary keys assigned
customer.LastOrderAt = order.PlacedAt; // found by DetectChanges at save
// One call: INSERT order, INSERT lines (FK fixed up), UPDATE customer,
// batched, in one implicit transaction.
await db.SaveChangesAsync(ct);
return order.Id; // real identity value from OUTPUT
}
}
// Table with a trigger: tell EF Core so it does not use OUTPUT without INTO.
modelBuilder.Entity<Order>().ToTable(t => t.HasTrigger("trg_Orders_Audit"));
SaveChanges inside a loop for every row. Why it is wrong: each call is its own round trip and transaction, losing batching and atomicity. Instead: save once per unit of work, or per chunk of a few hundred to a few thousand rows.SaveChanges only looks at entities you touched. Why it is wrong: DetectChanges scans every tracked entity, so a context holding 50,000 read-only entities makes every save slow. Instead: use AsNoTracking() for reads and short-lived contexts.AutoDetectChangesEnabled = false for speed and forgetting to call DetectChanges(). Why it is wrong: property changes on tracked entities are never noticed, so they are silently not saved. Instead: turn it off only around bulk Add loops, call ChangeTracker.DetectChanges() before saving, and restore it in a finally.MaxBatchSize to 1,000 to "go faster". Why it is wrong: large batches hit the 2,100-parameter limit and can be slower; the default was chosen by benchmark. Instead: measure, and use SqlBulkCopy or ExecuteUpdate for genuinely bulk work.SaveChanges in BeginTransaction "to be safe". Why it is wrong: it is already atomic. Instead: only add an explicit transaction when several saves or raw SQL must commit together.OUTPUT without INTO on a table with a trigger, so the save fails. Instead: declare HasTrigger in the model.SaveChanges and storing it elsewhere, for example in a message. Why it is wrong: it is a temporary value that will be replaced. Instead: use the navigation, read the id after the save, or use client-generated keys such as Guid.CreateVersion7().DbUpdateException and continuing with the same context. Why it is wrong: the failed changes are still tracked and will be sent again by the next save. Instead: discard the context or call ChangeTracker.Clear().SaveChanges already gives me a unit of work, batching and a transaction, which is why I don't wrap it in a hand-rolled Unit of Work or an explicit transaction without a reason. What I watch is the number of tracked entities: the pipeline is cheap for a request that touches ten rows and expensive for a job that tracks a hundred thousand. For those I chunk, clear the tracker, or skip it with ExecuteUpdate, ExecuteDelete or SqlBulkCopy.
| Option | When it fits | Cost | When not to |
|---|---|---|---|
One SaveChanges per use case |
Request-sized work | Snapshot scan of tracked set | Very large batches |
Chunked saves + ChangeTracker.Clear() |
Imports of tens of thousands of rows | Not atomic across chunks | When all-or-nothing is required |
ExecuteUpdate / ExecuteDelete |
Set-based changes | No tracker, no SaveChanges interceptors | Per-entity domain rules |
SqlBulkCopy |
Millions of inserts | No graph or key fix-up | Small or relational graphs |
Every object a DbContext knows about has an EntityState:
SaveChanges ignores it.SaveChanges sends an INSERT.SaveChanges sends an UPDATE of only the changed columns.SaveChanges sends a DELETE.Add, Attach, Update and Remove set states directly; DetectChanges compares current values with the snapshot taken at load time, flags each property that differs (IsModified) and moves the entity to Modified, which is why the UPDATE lists only those columns. Remove() on an Added entity just stops tracking it: no SQL. After a successful save, Added and Modified become Unchanged and Deleted becomes Detached. The trade-off: automatic tracking is convenient for small units of work, but it costs memory and CPU per entity, so reads should skip it.
A DbContext wraps one connection and one change tracker and allows one operation at a time; EF's concurrency detector throws when a second async operation starts before the first completes, usually from a shared context or a missing await. To run work in parallel, give each branch its own context (IDbContextFactory<T>.CreateDbContextAsync()), or combine the queries into one round trip. Never share a context across Task.WhenAll branches.
Every tracked entity costs an entry, an identity-map slot and an original-values snapshot, and DetectChanges scans all of them on every SaveChanges (and on Entries()/Entry()). On one long-lived context the tracked set keeps growing, so each save gets slower and the total becomes roughly quadratic, while memory climbs until the job runs out.
The fixes:
ChangeTracker.Clear() or use a new context per chunk.AsNoTracking() or projections.AutoDetectChangesEnabled around bulk Add loops and call DetectChanges once.ExecuteUpdate/ExecuteDelete, or SqlBulkCopy for millions of inserts.The trade-off: chunking gives up all-or-nothing atomicity, and bypassing the tracker skips interceptors and domain logic.
Last updated 23 Nov 2026.