Covers the five EF Core EntityState values, the operations that set each one, the SQL SaveChanges sends for each, and the state every entity ends in after a successful save.
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.
"EF Core tracks every entity it knows about with one of five states. Detached means the context doesn't know the object at all, which is where every
new Order()starts and where no-tracking query results stay. Unchanged is what a normal tracking query gives me: EF Core has the entity, plus a snapshot of the values it read, and believes it matches the row. Added means it will be inserted, Modified means at least one property differs from the snapshot, and Deleted means it will be removed.At
SaveChanges, EF Core first callsDetectChanges, which compares each Unchanged entity's current values with its snapshot and flips it to Modified, marking exactly which properties changed. Then it generates SQL per state: INSERT for Added, an UPDATE that sets only the modified columns for Modified, DELETE for Deleted, and nothing for Unchanged or Detached. After the commit it accepts the changes: Added and Modified become Unchanged with a fresh snapshot, generated keys are copied back, and Deleted entities become Detached.The mistake I see is people assuming EF Core saves whatever object they hold. If I build an entity from a request body and call
SaveChanges, nothing happens, because it is Detached. Or they callRemoveon something they just added and expect a DELETE; EF Core simply detaches it. The state is the contract: if I know what state each entity is in before I save, I know exactly what SQL will run."
| State | Meaning | How it gets there | SQL at SaveChanges |
|---|---|---|---|
| Detached | Not tracked | new, AsNoTracking(), after a delete is saved, ChangeTracker.Clear() |
None |
| Unchanged | Tracked, same as the snapshot | Tracking query, Attach() with a key, after a save |
None |
| Added | Will be inserted | Add(), Attach()/Update() on an entity with no key value, added to a tracked navigation |
INSERT |
| Modified | Some properties changed | DetectChanges finds a difference, Update(), Entry(e).Property(p).IsModified = true |
UPDATE of modified columns |
| Deleted | Will be removed | Remove() on a tracked entity, cascade from a deleted principal, orphaned required dependant |
DELETE |
| From | Operation | To |
|---|---|---|
| Unchanged | change a property, then DetectChanges |
Modified |
| Added | Remove() |
Detached (no SQL) |
| Modified | Entry(e).State = Unchanged |
Unchanged (changes discarded from the save) |
| Added / Modified | successful SaveChanges |
Unchanged |
| Deleted | successful SaveChanges |
Detached |
| Any | SaveChanges throws |
unchanged; nothing is accepted, so you can retry or discard |
db.Entry(order).State for one entity.db.ChangeTracker.Entries() for all of them (this calls DetectChanges first).db.ChangeTracker.DebugView.LongView in the debugger: every entity, its state and each modified property with original and current values.A support tool "saved" edits that never reached the database: the handler loaded the record with AsNoTracking(), changed it and called SaveChanges, which sent zero commands because the entity was Detached. Logging ChangeTracker.DebugView.ShortView before the save showed an empty tracker; loading the entity tracked fixed it, and an integration test now asserts the row changed.
Checks that the candidate knows the five states, how each is reached and what SQL each produces at SaveChanges.
Green flags
DetectChanges and the snapshot produce Modified.Red flags
State = Modified for every update.DbContext
└ ChangeTracker (public API)
└ StateManager (internal)
├ identity map: (entity type, key) -> InternalEntityEntry
└ InternalEntityEntry
├ Entity -> your object
├ EntityState -> Unchanged | Added | Modified | Deleted
├ original values snapshot (one slot per property)
└ modified flags (one bit per property)
Detached is not stored anywhere: it simply means there is no entry for the object.
By default EF Core uses snapshot change tracking. When an entity is materialised by a tracking query or attached, EF Core copies its property values into the snapshot. DetectChanges walks every tracked entry and compares current values with the snapshot. A difference sets the property's modified bit and moves the entry to Modified. DetectChanges runs automatically inside SaveChanges, Entries(), Entry() and a few other APIs, unless ChangeTracker.AutoDetectChangesEnabled is false.
SaveChanges
1. DetectChanges
2. collect entries in Added / Modified / Deleted
3. order commands by dependencies (principal inserts first, dependant deletes first)
4. build SQL per entry:
Added -> INSERT ... OUTPUT INSERTED.[Id]
Modified -> UPDATE ... SET only modified columns WHERE [Id] = @key
Deleted -> DELETE ... WHERE [Id] = @key
5. execute (batched, in a transaction if more than one statement)
6. AcceptAllChanges: Added/Modified -> Unchanged, Deleted -> Detached
For a Modified order where only Status changed:
SET NOCOUNT ON;
UPDATE [Orders] SET [Status] = @p0
OUTPUT 1
WHERE [Id] = @p1;
Adding a new OrderLine to a tracked order's Lines collection makes the line Added at the next DetectChanges. Removing a line from the collection severs the relationship: for a required relationship the orphan is marked Deleted (by default, DeleteOrphansTiming is immediate); for an optional one its foreign key is set to null and it becomes Modified.
The same row loaded in two contexts has two entries and two states. States are never shared across DbContext instances, which is one reason a context should live for one unit of work.
db.Entry(e).State before and after calling db.ChangeTracker.DetectChanges().db.ChangeTracker.DebugView.LongView after adding, modifying and removing three entities.Add an entity then Remove it, call SaveChanges with LogTo(Console.WriteLine), and confirm no SQL runs.SaveChanges fail (for example a unique index violation) and check the states afterwards.Watching the states change through one unit of work.
namespace Shop.Orders;
using Microsoft.EntityFrameworkCore;
public sealed class StateDemo(ShopDbContext db)
{
public async Task RunAsync(CancellationToken ct)
{
var order = await db.Orders.SingleAsync(o => o.Id == 42, ct);
Console.WriteLine(db.Entry(order).State); // Unchanged
order.Status = OrderStatus.Shipped;
db.ChangeTracker.DetectChanges(); // SaveChanges would do this for us
Console.WriteLine(db.Entry(order).State); // Modified
Console.WriteLine(db.Entry(order).Property(o => o.Status).IsModified); // True
var note = new OrderNote { OrderId = order.Id, Text = "Left at door" };
Console.WriteLine(db.Entry(note).State); // Detached
db.OrderNotes.Add(note);
Console.WriteLine(db.Entry(note).State); // Added
var old = await db.OrderNotes.FirstAsync(n => n.OrderId == order.Id, ct);
db.OrderNotes.Remove(old); // Deleted
Console.WriteLine(db.ChangeTracker.DebugView.ShortView);
// One transaction: UPDATE Orders (Status only), INSERT OrderNotes, DELETE OrderNotes
await db.SaveChangesAsync(ct);
Console.WriteLine(db.Entry(order).State); // Unchanged
Console.WriteLine(db.Entry(note).State); // Unchanged, note.Id now set
Console.WriteLine(db.Entry(old).State); // Detached
}
}
SaveChanges without Add or Attach. Why it is wrong: the object is Detached, so no SQL is sent and no error is raised. Instead: load the entity tracked and change it, or explicitly Add/Attach it.AsNoTracking() and expecting the save to persist it. Why it is wrong: no-tracking results are Detached. Instead: use a tracking query for entities you will modify.Entry(e).State = EntityState.Modified by habit. Why it is wrong: it marks every property modified, so the UPDATE writes every column and can overwrite other users' changes. Instead: let DetectChanges find real changes, or mark specific properties with IsModified.Remove() on a just-added entity to send a DELETE. Why it is wrong: EF Core simply stops tracking it, because the row never existed. Instead: understand that Added → Detached is a no-op in SQL.Entry(e).State with AutoDetectChangesEnabled = false and trusting it. Why it is wrong: without DetectChanges a changed entity still reports Unchanged. Instead: call ChangeTracker.DetectChanges() first, or leave auto-detect on.SaveChanges resets the states. Why it is wrong: entries keep their states, so a retry re-sends the same commands, and a long-lived context carries the failed changes into the next save. Instead: retry deliberately or call ChangeTracker.Clear() / use a fresh context.Entity states are the whole contract between my code and the SQL EF Core writes. When a bug report says "the update didn't save" or "it overwrote other columns", the first thing I check is the state of each entity just before SaveChanges, using ChangeTracker.DebugView. Almost every such bug is an entity in the wrong state: Detached when it should be Modified, or Modified on every column because someone used Update().
| Approach | When it fits | Cost | When not to |
|---|---|---|---|
Let DetectChanges set Modified |
Normal load-change-save | Snapshot per entity | Huge batches where the scan dominates |
Set state explicitly (Add, Remove) |
New and deleted entities | None beyond tracking | Never set Modified on the whole entity by habit |
Mark properties (IsModified) |
Disconnected partial updates | You must know what changed | When a tracked load is cheap enough |
ExecuteUpdate / ExecuteDelete |
Set-based changes | Skips the tracker entirely | When domain logic must run per entity |
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.
A tracking query (the default) adds every entity to the change tracker: EF Core keeps an identity map (one instance per key) and a snapshot of original values, so SaveChanges can detect edits. That costs memory and time.
AsNoTracking() skips both: fastest and leanest, but if the same row appears twice (e.g. the same customer on many orders via Include), you get separate instances.AsNoTrackingWithIdentityResolution() also skips the snapshot, but uses a temporary identity map during that query, so duplicates share one instance; the tracker is thrown away afterwards.I use tracking for entities I will modify, AsNoTracking for reads, and identity resolution when a no-tracking graph has shared references.
Update() attaches the entity graph and marks every property Modified, because EF Core has no snapshot of original values to compare against, so it can't tell which properties actually changed. It sends all columns, which silently overwrites (loses) other users' concurrent edits and wastes I/O. Instead: load the entity tracked and apply the DTO's changes (only changed columns are written); or attach and set Entry(e).Property(x => x.Name).IsModified = true for specific fields; or use ExecuteUpdate for set-based changes in one statement without loading. Always add a RowVersion concurrency token ([Timestamp] byte[]): EF Core adds it to the WHERE clause and throws DbUpdateConcurrencyException if someone else changed the row, which you turn into a 409.
Last updated 23 Nov 2026.