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

📚 Interview question

How does EF Core decide which SQL to run for SaveChanges, and in what order?

Beginner Theory Beginner

🎯 Key points

  • Change tracker runs DetectChanges against original-value snapshots
  • Commands ordered by FK dependencies
  • Batching (MaxBatchSize, default 42 on SQL Server)
  • Implicit transaction per SaveChanges, rolled back on failure
  • Key fix-up after identity values return
  • 0 rows affected on a concurrency token → DbUpdateConcurrencyException; other errors → DbUpdateException
  • SaveChangesAsync frees the request thread during I/O

⏱ 30-second answer

SaveChanges asks the change tracker to run DetectChanges, which compares every tracked entity with its original-value snapshot and sets its state (Added, Modified, Deleted). EF Core then builds INSERT, UPDATE and DELETE commands, orders them by foreign-key dependencies (principals inserted before dependents, dependents deleted first), batches them (SQL Server batches up to 42 statements per round trip by default) and runs them inside one implicit transaction unless you already opened one. Generated values (identity, rowversion) are read back and key fix-up updates foreign keys and navigations. If an UPDATE or DELETE touches 0 rows because a concurrency token changed, EF Core throws DbUpdateConcurrencyException; any other database error rolls back the whole transaction and surfaces as DbUpdateException. SaveChangesAsync does the same work but awaits the network I/O, so request threads are not blocked; prefer it in ASP.NET Core.

🗣 Full answer (senior)

How I would answer this in an interview

"SaveChanges is driven by the change tracker. First it calls DetectChanges, which walks every tracked entity and compares current property values with the snapshot taken when the entity was attached or loaded. That gives each entity a state: Added, Modified, Deleted or Unchanged. From those states EF Core builds commands: an INSERT per added entity, an UPDATE with only the modified columns, a DELETE per deleted entity.

Then it orders them. Foreign keys decide the order: principals are inserted before dependents, dependents are deleted before principals. The SQL Server provider batches commands, up to 42 per round trip by default, and wraps the whole thing in one transaction unless I already started one. After the commands run, EF Core reads back generated values such as identity keys and rowversions and does key fix-up, so order.Lines[0].OrderId now holds the new identity.

The failure paths matter as much. If an UPDATE or DELETE that includes a concurrency token affects 0 rows, EF Core throws DbUpdateConcurrencyException; any other database error throws DbUpdateException and the transaction rolls back, so nothing is half-saved. In an API I always use SaveChangesAsync, because the work is network I/O and blocking a thread pool thread for it costs throughput."


The steps

Step What happens
1. DetectChanges Snapshot comparison sets entity states (skipped if AutoDetectChangesEnabled = false)
2. Command building INSERT / UPDATE (changed columns only) / DELETE per entity
3. Ordering Topological sort by foreign keys
4. Batching Up to MaxBatchSize (42 by default on SQL Server) per round trip
5. Transaction Implicit, unless Database.BeginTransaction() or an ambient transaction exists
6. Propagation Generated keys and rowversions read back, key fix-up, states set to Unchanged

Errors

Exception Cause Typical handling
DbUpdateConcurrencyException 0 rows affected for a row with a concurrency token Reload, merge or return HTTP 409
DbUpdateException Constraint violation, deadlock, timeout Map unique-key violations (SQL error 2601/2627) to 409; let retries handle transient errors

Production example

In an order import, saving 5,000 lines one SaveChanges per row took [~90 seconds]; one SaveChanges per 1,000 rows used ~24 batched round trips per chunk and finished in [~6 seconds], with each chunk atomic.

🔍 What the interviewer is checking

Checks knowledge of change tracking and command ordering.

↩ Usually asked after

More in EF Core Fundamentals

Last updated 23 Nov 2026.

🌐 Sangam's Webring

⏪ Previous 🏠 Main Next ⏩
💬 Chat with me