skip to content

In EF Core 10, what are the five EntityState values, and what does SaveChanges do with an entity in each one?

level: juniorimportance: must knowfreq 72%

answer

  1. tracked or not tracked
  2. queried entities start Unchanged
  3. Added, Modified, Deleted map to SQL verbs
  4. Deleted becomes Detached after saving
  5. Remove on an Added entity

basics

~10 s

EntityState has five values: Detached, Unchanged, Added, Modified and Deleted. SaveChanges inserts Added entities, updates Modified ones, deletes Deleted ones and skips the rest; afterwards Added and Modified become Unchanged and Deleted become Detached.

solid answer

~40 s

Every entity a `DbContext` knows about has an `EntityState`. `Detached` means the context is not tracking it at all; `Unchanged` is what a tracking query returns; `Added` comes from `Add` and means an `INSERT`; `Modified` means at least one property is marked modified and produces an `UPDATE` of the modified columns; `Deleted` comes from `Remove` and produces a `DELETE`. Nothing reaches the database when a property is set or `Remove` is called - only `SaveChanges` or `SaveChangesAsync` writes. When the save succeeds, EF Core accepts the changes: `Added` and `Modified` entries become `Unchanged`, `Deleted` entries become `Detached`. One trap: `Remove` on an entity that is still `Added` simply detaches it, because there is no row to delete.

code

csharp · 14 lines
csharp
var customer = await db.Customers.SingleAsync(c => c.Id == id);
// db.Entry(customer).State == EntityState.Unchanged

customer.Phone = "+44 20 7946 0000";
// still Unchanged until change detection runs

var lead = new Customer { Name = "Ada Lovelace" };
db.Customers.Add(lead);            // Added

var stale = await db.Customers.SingleAsync(c => c.Id == staleId);
db.Customers.Remove(stale);        // Deleted

await db.SaveChangesAsync();       // UPDATE, INSERT, DELETE
// customer and lead: Unchanged; stale: Detached

go deeper

for a junior

Name all five states and the SQL verb each one produces on SaveChanges, and say that a tracking query returns Unchanged entities.

for a middle

Explain that state is per entity but modification is per property, and what accepting changes does to Added, Modified and Deleted entries after a successful save.

for a senior

Use DebugView and Entries() to explain an unexpected INSERT or full-row UPDATE in a code review, and know when assigning State differs from calling Remove.

for a principal

Judge where a team should let tracking infer states and where explicit state assignment makes write behaviour clearer for reviewers.

## What an entity state is EF Core's **change tracker** is the part of a `DbContext` that remembers which objects it has seen and what should happen to each of them on the next save. Each tracked object has an **entry** (an `EntityEntry`), and every entry carries one value of the `EntityState` enum. The state is EF Core's verdict on the object: leave it alone, insert it, update it or delete it. You read or set it through `context.Entry(customer).State`. Take a CRM back end with a `Customer` entity. A support agent opens a profile, edits the phone number and saves. Behind that one click the customer moves through several states. ## The five values | `EntityState` | Tracked by the context | Row exists in the database | What `SaveChanges` does | |---|---|---|---| | `Detached` | No | unknown to EF Core | nothing | | `Unchanged` | Yes | yes | nothing | | `Added` | Yes | not yet | `INSERT` | | `Modified` | Yes | yes | `UPDATE` of the modified columns | | `Deleted` | Yes | yes | `DELETE` | EF Core tracks changes **per property**: an entity is `Modified` exactly when at least one of its properties is marked modified, and the `UPDATE` sets only those columns for an entity that came from a query. ## How an entity reaches each state - **A tracking query** (the default) returns entities in `Unchanged`, and keeps a snapshot of the values it read. - **`Add` / `AddAsync`** puts a new object, and anything reachable from it that is not yet tracked, into `Added`. - **Changing a property** of a tracked entity does not change the state at that moment under the default snapshot tracking; EF Core notices the edit when change detection runs (`SaveChanges` runs it for you) and then moves the entity to `Modified`. - **`Remove`** marks a tracked or untracked entity `Deleted` - unless the entity is `Added`, in which case it becomes `Detached`, since there is nothing in the database to delete. - **`Attach` and `Update`** start tracking an object that came from outside the context, as `Unchanged` and `Modified` respectively (with `Added` for objects whose generated key is unset). - **Setting `Entry(x).State` directly** forces exactly the state you assign, for that one entity only. ## What happens during and after SaveChanges 1. EF Core detects changes, so edits made since the last check are reflected in the states. 2. It builds `INSERT`, `UPDATE` and `DELETE` commands for the `Added`, `Modified` and `Deleted` entries and sends them to the database. 3. Store-generated values, such as an identity key, are read back into the entities. 4. On success it **accepts all changes**: `Added` and `Modified` entries become `Unchanged` with fresh original values, and `Deleted` entries become `Detached`. So after a successful save, a context that is still alive tracks the inserted and updated customers as `Unchanged` and no longer tracks the deleted ones. If the save throws, the changes are not accepted, so the entries keep their states and the unit of work can be inspected or retried. ## Seeing the states while debugging - `context.Entry(customer).State` gives one entity's state. - `context.ChangeTracker.Entries()` enumerates every entry; `Entries<Customer>()` filters by type. - `context.ChangeTracker.DebugView.ShortView` prints one line per tracked entity with its state; `LongView` adds every property, marking modified ones and their original values. ## Mistakes interviewers listen for - Believing a property setter writes to the database. EF Core writes only on `SaveChanges`. - Confusing `Detached` with "deleted". `Detached` only means this context is not tracking the object; the row may well exist. - Assuming a `Modified` entity always rewrites the whole row. That is true after `Update` or `State = EntityState.Modified`, which mark every property, but not for a queried entity whose single property changed. - Expecting an entity you just saved as deleted to still be visible through `Entries()`. It is gone from the tracker. - Setting `State = EntityState.Deleted` on an `Added` entity and expecting it to behave like `Remove`. Assigning the state forces `Deleted` regardless of the current state; `Remove` is the call that detaches an unsaved addition.

  • What happens when you call Remove on a Customer that is still in the Added state?
    `Remove` detaches it: the entity moves from `Added` to `Detached`, and `SaveChanges` sends neither an `INSERT` nor a `DELETE` for it, because the row never existed. Assigning `Entry(customer).State = EntityState.Deleted` is different - it forces `Deleted` whatever the current state is.
  • How do you see what a DbContext is about to write while debugging?
    Read `context.ChangeTracker.DebugView.ShortView` for one line per tracked entity with its state, or `LongView` for every property with modified flags and original values. `ChangeTracker.Entries()` gives the same data as `EntityEntry` objects you can filter in code; it runs change detection first, so the states it reports are current.

  • Setting a property on a tracked entity sends an UPDATE straight away.
  • Entities returned by a tracking query start in the Added state.
  • Detached means the row has been deleted from the database.
  • After SaveChanges a deleted entity stays tracked in the Deleted state.
  • A Modified entity loaded by a query always has every column rewritten.