Entity Framework Core Intermediate

Change tracking and SaveChanges

EF Core remembers the entities it loads and notices when you change them, so SaveChanges knows exactly what to write. This lesson explains entity states, how SaveChanges works, and how to handle entities that were not loaded by the current context.

How change tracking leads to SQL
  1. StartQuery loads an entityThe context stores it as Unchanged with a snapshot
  2. Step 2You change a propertyproduct.Price = 450
  3. Step 3SaveChangesAsync is calledDetectChanges compares values with the snapshot
  4. Step 4State becomes ModifiedOnly the Price column is marked as changed
  5. Step 5SQL is generatedUPDATE Products SET Price = @p0 WHERE Id = @p1, in a transaction
  6. EndBack to UnchangedThe snapshot is refreshed after a successful save

The idea in plain words

Every entity a DbContext knows about has a state: Added, Unchanged, Modified, Deleted or Detached. Queries return entities in the Unchanged state. Calling Add marks an entity Added, Remove marks it Deleted, and changing a property makes it Modified. SaveChanges turns those states into INSERT, UPDATE and DELETE statements and runs them in a single transaction.

Tracking costs memory and time, so for data you only display, use AsNoTracking.

Example

C#
var product = await db.Products.FirstAsync(p => p.Id == 7);   // Unchanged
product.Price = 450;                                            // will be Modified

db.Products.Add(new Product { Name = "Desk lamp", Price = 999 }); // Added

var old = await db.Products.FindAsync(3);
if (old is not null) db.Products.Remove(old);                   // Deleted

Console.WriteLine(db.ChangeTracker.DebugView.ShortView);        // see the states
var affected = await db.SaveChangesAsync();                     // one transaction

Disconnected entities

In web apps the object you want to save often comes from a form or an API call, not from this context. Update attaches it and marks every property Modified. Loading the entity first and copying the changed values is usually safer, because only real changes are written and over-posting is avoided.

C#
// Option 1: attach and mark everything modified
db.Products.Update(productFromForm);

// Option 2 (usually better): load, then copy from a view model.
// SetValues copies only properties whose names match.
var entity = await db.Products.FindAsync(form.Id);
db.Entry(entity!).CurrentValues.SetValues(form); // form: ProductForm view model
await db.SaveChangesAsync();

Common mistakes

  • Changing entities loaded with AsNoTracking and expecting SaveChanges to notice.
  • Calling SaveChanges inside a loop for every row instead of once at the end.
  • Keeping one context alive for a long time, so it tracks thousands of entities and gets slow.

Interview question

What happens when you call SaveChanges in EF Core?

EF Core runs DetectChanges to compare tracked entities with their original snapshots, works out which entities are Added, Modified or Deleted, orders the commands to respect relationships, and sends the INSERT, UPDATE and DELETE statements to the database inside a transaction (batched where possible). Generated values such as identity keys are read back into the entities, the states are reset to Unchanged, and the number of affected rows is returned.

Your progress is saved only in this browser.

Want the full details? Read the official Microsoft documentation for this topic.