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

📚 Interview question

What are the entity states in EF Core (Added, Unchanged, Modified, Deleted and Detached)? How does an entity move between them, and what does SaveChanges do with each state?

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.

Junior Theory Beginner change-tracking dbcontext ef-core entity-state savechanges sql-server

🎯 Key points

  • Five EntityState values: Detached, Unchanged, Added, Modified, Deleted
  • Tracking query results start Unchanged; new objects are Detached until Add/Attach
  • Added → INSERT, Modified → UPDATE of changed columns only, Deleted → DELETE, Unchanged/Detached → nothing
  • After a successful save: Added and Modified become Unchanged, Deleted becomes Detached
  • Modified is found by DetectChanges comparing the original-values snapshot, not by you
  • Remove() on an Added entity just detaches it: no SQL
  • Inspect with db.Entry(e).State and ChangeTracker.DebugView.LongView

⏱ 30-second answer

Every object a DbContext knows about has an EntityState:

  • Detached: not tracked; SaveChanges ignores it.
  • Unchanged: tracked, matches the database (what a tracking query returns).
  • Added: new; SaveChanges sends an INSERT.
  • Modified: one or more properties changed; SaveChanges sends an UPDATE of only the changed columns.
  • Deleted: marked for removal; 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.

🗣 Full answer (senior)

How I would answer this in an interview

"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 calls DetectChanges, 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 call Remove on 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."


The five states

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

Transitions worth knowing

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

How to see the states

  • 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.

Production example

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.

🔍 What the interviewer is checking

Checks that the candidate knows the five states, how each is reached and what SQL each produces at SaveChanges.

Green flags

  • Names all five states, including Detached.
  • Explains that DetectChanges and the snapshot produce Modified.
  • Knows an UPDATE only includes the changed columns.
  • Knows the post-save transitions (Added/Modified → Unchanged, Deleted → Detached).

Red flags

  • Thinks EF Core saves any object you hold.
  • Sets State = Modified for every update.
  • Cannot say what happens to a removed Added entity.

📚 Learn in depth

1. Where the state lives

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.

2. How Modified is discovered

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.

3. What SaveChanges does per state

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;

4. Navigations change states too

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.

5. States are per context

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.

Try it yourself

  1. Load an entity, change one property, and print db.Entry(e).State before and after calling db.ChangeTracker.DetectChanges().
  2. Print db.ChangeTracker.DebugView.LongView after adding, modifying and removing three entities.
  3. Add an entity then Remove it, call SaveChanges with LogTo(Console.WriteLine), and confirm no SQL runs.
  4. Remove a line from a tracked order's collection and check whether it becomes Deleted or Modified with a required vs optional foreign key.
  5. Make SaveChanges fail (for example a unique index violation) and check the states afterwards.

💻 Code

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
    }
}

⚠ Common mistakes

  • Mistake: Building an entity from a request and calling 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.
  • Mistake: Changing an entity loaded with 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.
  • Mistake: Setting 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.
  • Mistake: Expecting 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.
  • Mistake: Reading 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.
  • Mistake: Assuming a failed 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.
  • Mistake: Thinking Unchanged means "identical to the database right now". Why it is wrong: it only means identical to the snapshot taken at load time; another user may have changed the row since. Instead: use a concurrency token when that matters.

🏛 Senior insight: trade-offs

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

🔗 Follow-ups the interviewer may ask

  1. When: Candidate mentions DetectChanges or the snapshot. Why: Checks whether the candidate understands what happens inside SaveChanges, not just the states.
    How to answer

    SaveChanges runs a pipeline:

    1. 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).
    2. Ordering: builds commands per entity and sorts them by the foreign-key graph, so principals are inserted before dependants and dependants deleted before principals.
    3. Batching: groups commands into as few round trips as possible (SQL Server's default MaxBatchSize is 42).
    4. Transaction: wraps them in an implicit transaction when more than one statement is needed, or joins your explicit one.
    5. Fix-up: on SQL Server, 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.

  2. When: Candidate mentions that no-tracking results are Detached. Why: Checks the cost and identity trade-offs of tracking vs no-tracking queries.
    How to answer

    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.

  3. When: Candidate mentions setting State = Modified or calling Update(). Why: Checks the risk of marking every column modified for disconnected entities.
    How to answer

    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.

↩ Usually asked after

More in Change Tracking

Last updated 23 Nov 2026.

🌐 Sangam's Webring

⏪ Previous 🏠 Main Next ⏩
💬 Chat with me