What actually happens when you call SaveChanges in EF Core?

Entity Framework & EF Core Persistence Intermediate 2–3 Yrs3–5 Yrs Conceptual 1 min read

Quick Answer

SaveChanges runs DetectChanges (diffs tracked entities against their snapshots), works out the ordered set of INSERT/UPDATE/DELETE statements respecting FK dependencies, wraps them in a single transaction, sends them (batched), reads back generated keys and concurrency tokens, and — on success — resets entity states to Unchanged.

SaveChanges first detects what changed by comparing every tracked entity to the snapshot it took when the entity was loaded. Then it figures out the statements needed and the order — parents before children for inserts, the reverse for deletes — batches them, and runs them all inside one transaction. If everything succeeds it reads back any database-generated values like identity ids and rowversions into the entities and marks them all unchanged. If it fails, the transaction rolls back, but the in-memory state isn't reset, so I'm careful about retries.

  • It's atomic: if any statement fails, the whole transaction rolls back — but the in-memory entity states are not reset, so a naive retry can double-apply. Handle carefully.
  • EF Core batches multiple statements into one round trip (configurable batch size) — a big win over EF6.
  • Order is computed from the dependency graph (insert parents before children, delete children before parents).
  • Generated values (identity, rowversion) flow back into the tracked entities.