📁 Sangam Dhakal - Portfolio v2.0 - Netscape Navigator 4.0
_
□
×

📚 Interview question

How does SaveChanges work in EF Core? Walk through DetectChanges and snapshot tracking, how EF Core orders and batches the commands, the implicit transaction, and how generated keys and foreign keys are fixed up afterwards.

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.

Intermediate Theory Intermediate batching change-tracking ef-core savechanges sql-server transactions

🎯 Key points

  • SaveChanges calls DetectChanges first (unless AutoDetectChangesEnabled is false)
  • Snapshot tracking: compares current values to the original-values snapshot; only changed columns go in the UPDATE
  • Commands are ordered by the foreign key graph: principal inserts before dependants, dependant deletes before principals
  • Commands are batched; SQL Server default MaxBatchSize is 42, configurable on UseSqlServer
  • Implicit transaction when more than one statement (AutoTransactionBehavior.WhenNeeded); an ambient or explicit transaction is reused
  • Generated values come back via OUTPUT INSERTED (watch triggers: HasTrigger / UseSqlOutputClause(false))
  • Temporary key values replaced by real ones and propagated to foreign keys and navigations (fix-up)
  • On failure nothing is accepted: states stay as they were, and the transaction is rolled back

⏱ 30-second answer

SaveChanges runs a pipeline:

  1. 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).
  2. Ordering: builds commands per entity and sorts them by the foreign-key graph, so principals are inserted before dependants and dependants deleted before principals.
  3. Batching: groups commands into as few round trips as possible (SQL Server's default MaxBatchSize is 42).
  4. Transaction: wraps them in an implicit transaction when more than one statement is needed, or joins your explicit one.
  5. Fix-up: on SQL Server, 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.

🗣 Full answer (senior)

How I would answer this in an interview

"SaveChanges is a small unit-of-work engine. First it calls DetectChanges. 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 why SaveChanges gets 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 with MaxBatchSize. 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 ambient TransactionScope, it uses that instead.

Finally, generated values come back through an OUTPUT clause: 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 calling SaveChanges inside a loop, once per row: that throws away batching and the single transaction, and turns one round trip into thousands."


The pipeline

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)

AutoTransactionBehavior

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)

Disconnected entities

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.

Production example

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.

🔍 What the interviewer is checking

Checks whether the candidate understands what happens inside SaveChanges: change detection, ordering, batching, transactions and key fix-up.

Green flags

  • Explains snapshot comparison and why only changed columns are updated.
  • Knows commands are ordered by relationships and batched.
  • Knows SaveChanges is atomic on its own and when it opens a transaction.
  • Mentions temporary keys and fix-up via OUTPUT.

Red flags

  • Calls SaveChanges per row by habit.
  • Thinks each entity is a separate round trip.
  • Wraps every save in an explicit transaction without knowing why.

📚 Learn in depth

1. Snapshot vs notification tracking

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.

2. Ordering by the dependency graph

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.

3. Batching on SQL Server

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.

4. OUTPUT and triggers

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.

5. Temporary keys and fix-up

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.

6. Failure

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.

7. Events and interceptors

SavingChanges, SavedChanges and SaveChangesFailed events, and ISaveChangesInterceptor, run around this pipeline. That is where audit columns and soft delete are usually implemented.

Try it yourself

  1. Add 100 entities and save with LogTo(Console.WriteLine, LogLevel.Information); count the commands, then set MaxBatchSize(10) and count again.
  2. Insert an order with lines and check db.Entry(order).Property(o => o.Id).IsTemporary before and after saving.
  3. Add a trigger to a table and observe the error; fix it with HasTrigger.
  4. Time 5,000 inserts with SaveChanges per row vs per 1,000 rows using BenchmarkDotNet or a Stopwatch.
  5. Set AutoTransactionBehavior.Never in a test and make the third statement fail to see a partial save.

💻 Code

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"));

⚠ Common mistakes

  • Mistake: Calling 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.
  • Mistake: Believing 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.
  • Mistake: Setting 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.
  • Mistake: Raising 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.
  • Mistake: Wrapping a single 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.
  • Mistake: Ignoring triggers on legacy tables. Why it is wrong: SQL Server rejects OUTPUT without INTO on a table with a trigger, so the save fails. Instead: declare HasTrigger in the model.
  • Mistake: Reading a generated id before 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().
  • Mistake: Catching a 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().

🏛 Senior insight: trade-offs

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

🔗 Follow-ups the interviewer may ask

  1. When: Candidate is unsure which state produces which SQL. Why: Checks the entity-state basics the pipeline is built on.
    How to answer

    Every object a DbContext knows about has an EntityState:

    • Detached: not tracked; SaveChanges ignores it.
    • Unchanged: tracked, matches the database (what a tracking query returns).
    • Added: new; SaveChanges sends an INSERT.
    • Modified: one or more properties changed; SaveChanges sends an UPDATE of only the changed columns.
    • Deleted: marked for removal; 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.

  2. When: Candidate mentions the DbContext as a unit of work. Why: Checks that the candidate knows a context is not thread-safe and how to parallelise database work.
    How to answer

    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.

  3. When: Candidate mentions DetectChanges scanning every tracked entity. Why: Checks change tracker performance at scale and when to bypass it.
    How to answer

    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:

    • Chunk: save every few hundred to few thousand entities, then ChangeTracker.Clear() or use a new context per chunk.
    • Read with AsNoTracking() or projections.
    • Turn off AutoDetectChangesEnabled around bulk Add loops and call DetectChanges once.
    • For set-based changes, skip the tracker with 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.

↩ Usually asked after

More in Change Tracking

Last updated 23 Nov 2026.

🌐 Sangam's Webring

⏪ Previous 🏠 Main Next ⏩
💬 Chat with me