Skip to content
Search lessons, topics, tests…
Esc

    ↑ ↓ moveEnter openEsc close
    Lesson2 / 21

    Change Tracking: Entity States, Snapshots, DetectChanges and the Identity Map

    EF Core change tracking records entity states and detects property edits so SaveChanges can write inserts, updates and deletes.

    The important distinction is between changing an object, recording that change, and writing it to the database. These do not necessarily happen at the same moment.

    By the end, you can predict the SQL for an edit, inspect what EF Core plans to save, and explain why querying the same row again may return old values. If you need a refresher on SQL logging, start with how EF Core runs a query.

    What are the five entity states in EF Core?

    The change tracker is the part of a DbContext that records the entities it is working with and their pending changes. Each tracked entity has an entry: EF Core's record of its state and property information.

    An entity's state tells EF Core what kind of work to perform when you save:

    StateMeaningDatabase write on SaveChanges
    DetachedThis context is not tracking the entity.None
    AddedThe entity is waiting to be inserted.INSERT
    UnchangedThe entity has no recorded changes to save.None
    ModifiedThe entity has properties marked for updating.UPDATE
    DeletedThe entity is waiting to be deleted.DELETE

    A tracking query registers the entity instances it returns with the context. Entity queries use tracking by default, and newly tracked query results start as Unchanged.

    You can also start tracking explicitly:

    • Add normally marks a new entity as Added.
    • Attach normally marks an existing entity with a supplied key as Unchanged.
    • Update normally marks an existing entity with a supplied key as Modified.

    These methods can also reach connected entities. A navigation property is a property that refers to a related entity or collection of related entities. Adding a new entity to a tracked entity's navigation can cause EF Core to discover and track it during change detection.

    The mistake to avoid. Changing an entity's state does not execute SQL. For example, Add schedules an insert; SaveChanges performs it.

    In an interview, say: “EF Core has five entity states. Detached means not tracked. Added means insert, Modified means update, and Deleted means delete when saved. Unchanged produces no write. Setting a state alone does not send SQL.”

    How do snapshots and DetectChanges find edits?

    By default, EF Core uses snapshot tracking. A snapshot is a stored copy of an entity's property values, captured when tracking begins. These stored values are its original values; the values on the object now are its current values.

    DetectChanges compares current values with the stored originals to find property edits.

    With ordinary property assignments, the object can change before its entry's state changes. EF Core needs a detection pass to record that edit.

    Normally, these operations trigger detection automatically:

    • SaveChanges, before writing to the database.
    • ChangeTracker.Entries(), before returning entry information.
    • ChangeTracker.HasChanges(), before reporting whether there is work to save.

    You can request detection directly with ChangeTracker.DetectChanges(). If you disable automatic detection through AutoDetectChangesEnabled, explicitly detect ordinary property edits before saving.

    The mistake to avoid. An ordinary property assignment does not necessarily mark the entity Modified immediately. The object may contain the new value while the tracker still reports Unchanged until detection runs.

    In an interview, say: “Default snapshot tracking compares current values with originals captured when tracking starts. SaveChanges, Entries and HasChanges normally trigger detection. If I disable automatic detection, I must explicitly detect ordinary property edits before saving.”

    How can I inspect entity states and changed columns?

    The next program uses EF Core 10.0.12 with SQLite in memory; keeping the connection open keeps the database alive.

    Before running it, predict:

    1. The state before and after Add.
    2. The state immediately after assigning a new name, before detection.
    3. Whether the update writes Name, Stock, or both.
    4. The state after a successful delete.

    The program prints actual database commands as well as entry information. Command timestamps and execution durations will differ between runs.

    C#
    using Microsoft.Data.Sqlite;
    using Microsoft.EntityFrameworkCore;
    using Microsoft.EntityFrameworkCore.Diagnostics;
    
    using var connection = new SqliteConnection("Data Source=:memory:");
    connection.Open();
    
    bool logSql = false;
    var options = new DbContextOptionsBuilder<ShopContext>()
        .UseSqlite(connection)
        .LogTo(message =>
        {
            if (logSql)
                Console.WriteLine(message);
        }, new[] { RelationalEventId.CommandExecuted })
        .Options;
    
    using var db = new ShopContext(options);
    db.Database.EnsureCreated();
    logSql = true;
    
    var product = new Product { Name = "Pencil", Stock = 10 };
    var entry = db.Entry(product);
    Console.WriteLine($"Before Add: {entry.State}");
    
    db.Add(product);
    Console.WriteLine($"After Add: {entry.State}");
    var inserted = db.SaveChanges();
    Console.WriteLine($"Insert: entries={inserted}; state={entry.State}; id={product.Id}");
    
    product.Name = "Blue pencil";
    Console.WriteLine($"Before detection: {entry.State}");
    db.ChangeTracker.DetectChanges();
    Console.WriteLine($"After detection: {entry.State}");
    
    var name = entry.Property(p => p.Name);
    Console.WriteLine($"Name: original={name.OriginalValue}; current={name.CurrentValue}");
    Console.WriteLine($"Name modified: {name.IsModified}");
    Console.WriteLine($"Stock modified: {entry.Property(p => p.Stock).IsModified}");
    Console.WriteLine(db.ChangeTracker.DebugView.LongView);
    
    var updated = db.SaveChanges();
    Console.WriteLine($"Update: entries={updated}; state={entry.State}");
    
    db.Remove(product);
    Console.WriteLine($"Before delete save: {entry.State}");
    var deleted = db.SaveChanges();
    Console.WriteLine($"Delete: entries={deleted}; state={entry.State}");
    
    public sealed class ShopContext : DbContext
    {
        public ShopContext(DbContextOptions<ShopContext> options) : base(options) { }
        public DbSet<Product> Products => Set<Product>();
    }
    
    public sealed class Product
    {
        public int Id { get; set; }
        public string Name { get; set; } = "";
        public int Stock { get; set; }
    }
    Output
    Before Add: Detached
    After Add: Added
    info: 12/01/2026 06:49:51.979 RelationalEventId.CommandExecuted[20101] (Microsoft.EntityFrameworkCore.Database.Command)
          Executed DbCommand (2ms) [Parameters=[@p0='?' (Size = 6), @p1='?' (DbType = Int32)], CommandType='Text', CommandTimeout='30']
          INSERT INTO "Products" ("Name", "Stock")
          VALUES (@p0, @p1)
          RETURNING "Id";
    Insert: entries=1; state=Unchanged; id=1
    Before detection: Unchanged
    After detection: Modified
    Name: original=Pencil; current=Blue pencil
    Name modified: True
    Stock modified: False
    Product {Id: 1} Modified
        Id: 1 PK
        Name: 'Blue pencil' Modified Originally 'Pencil'
        Stock: 10
    
    info: 12/01/2026 06:49:52.013 RelationalEventId.CommandExecuted[20101] (Microsoft.EntityFrameworkCore.Database.Command)
          Executed DbCommand (0ms) [Parameters=[@p1='?' (DbType = Int32), @p0='?' (Size = 11)], CommandType='Text', CommandTimeout='30']
          UPDATE "Products" SET "Name" = @p0
          WHERE "Id" = @p1
          RETURNING 1;
    Update: entries=1; state=Unchanged
    Before delete save: Deleted
    info: 12/01/2026 06:49:52.020 RelationalEventId.CommandExecuted[20101] (Microsoft.EntityFrameworkCore.Database.Command)
          Executed DbCommand (0ms) [Parameters=[@p0='?' (DbType = Int32)], CommandType='Text', CommandTimeout='30']
          DELETE FROM "Products"
          WHERE "Id" = @p0
          RETURNING 1;
    Delete: entries=1; state=Detached

    Needs the package Microsoft.EntityFrameworkCore.Sqlite 10.0.12. Built and run with it: the output above is what the program really printed.

    A property's modification flag, exposed as IsModified, records whether EF Core plans to update that property. Only Name is flagged, so the SET clause names only Name; the ID only identifies the row in WHERE. RETURNING 1 is SQLite's way of confirming the row.

    Entry(entity) gives access to one entity's state, original values, current values and property flags. DebugView.ShortView lists tracked entities, keys and states. DebugView.LongView, used above, also shows property and navigation information.

    Run DetectChanges before reading DebugView after ordinary edits when you need its state and flags to be current. Calling db.Entry(product) runs change detection for that one entity. So the program calls Entry once at the start and keeps the result in entry. Reading entry.State later does not run detection, so you can see the state before DetectChanges.

    Remove marks a saved entity Deleted, and a successful save makes it Detached. Remove on an entity that is still Added (never saved) makes it Detached at once, and no SQL is sent for it.

    The mistake to avoid. A debug view can show a new current value alongside an old state if detection has not run. Do not interpret that combination as proof that EF Core will ignore the edit during a normal save.

    In an interview, say: “I inspect Entry for one entity's state and property flags, or DebugView for the tracker as a whole. After ordinary edits, I run DetectChanges before reading DebugView so its states and modified flags are current.”

    Does EF Core update every column?

    For normal tracked edits, EF Core marks the changed properties and updates those columns. That is why changing only Name in the previous example leaves Stock out of the update.

    An object built from a request is different: Update marks every non-key property modified, so a field the request left out is written with its default value. Lesson 4, updating data from an API, shows the safe ways.

    In an interview, say: “Normal tracked edits update changed columns. Update, or setting the entity state to Modified, marks non-key properties as modified. Attach alone schedules no update for an existing entity. EF Core does not infer which request fields were supplied.”

    What does SaveChanges actually do?

    For the tracked work in these examples, a normal SaveChanges call proceeds through these steps:

    1. Detect changes. With automatic detection enabled, EF Core records outstanding ordinary property edits.
    2. Prepare and order writes. It uses entity states and property flags to build commands, ordering them to respect database relationships.
    3. Execute the writes. It uses a transaction when needed. A transaction groups database operations so they can succeed or fail together.
    4. Read generated values. Values produced by the database, such as an inserted product ID, are copied back into tracked entities.
    5. Accept changes after success. By default, EF Core updates its tracking records to reflect the saved result.

    With successful default acceptance, Added and Modified entries become Unchanged. Deleted entries become Detached. Saved current values become the new original values for the entries that remain tracked.

    flowchart TD
        A["Added"] -->|"save succeeds"| U["Unchanged"]
        M["Modified"] -->|"save succeeds"| U
        U -->|"Remove"| D["Deleted"]
        D -->|"save succeeds"| X["Detached"]

    The SaveChanges return value is the number of state entries written to the database, not a count of SQL rows affected or commands executed.

    For relational providers that support transactions, the default behavior makes the changes in a single save transactional. You do not normally need an explicit transaction for one save; the transactions lesson covers the details.

    The mistake to avoid. The return value is not a SQL row count. Tracking entries and affected database rows are different measures, even when a small example happens to produce the same number.

    In an interview, say: “SaveChanges normally detects changes, orders and executes writes, uses a transaction when needed, and reads generated values. After successful default acceptance, Added and Modified become Unchanged, and Deleted becomes Detached. It returns state entries written, not SQL rows affected.”

    Does a tracking query return fresh values?

    The identity map is the context's lookup from an entity type and primary key to its tracked instance. Identity resolution means reusing that instance whenever the same entity is encountered again.

    A context needs one tracked instance for a given entity type and primary key. Otherwise, it could have two different names, stock values or relationships for the same entity, with no clear answer about which to save.

    A tracking query still runs against the database, so the identity map is not a cache of query results.

    This independent SQLite program makes the difference visible. A second context changes the database directly while the first context still holds the product. Predict the names before and after Reload.

    C#
    using Microsoft.Data.Sqlite;
    using Microsoft.EntityFrameworkCore;
    using Microsoft.EntityFrameworkCore.Diagnostics;
    
    using var connection = new SqliteConnection("Data Source=:memory:");
    connection.Open();
    
    bool logSql = false;
    var options = new DbContextOptionsBuilder<IdentityContext>()
        .UseSqlite(connection)
        .LogTo(message =>
        {
            if (logSql)
                Console.WriteLine(message);
        }, new[] { RelationalEventId.CommandExecuted })
        .Options;
    
    using (var setup = new IdentityContext(options))
    {
        setup.Database.EnsureCreated();
        setup.Products.Add(new IdentityProduct { Id = 1, Name = "Pencil" });
        setup.SaveChanges();
    }
    
    logSql = true;
    using var db = new IdentityContext(options);
    var first = db.Products.Single(p => p.Id == 1);
    Console.WriteLine($"After query: {db.Entry(first).State}");
    
    using (var writer = new IdentityContext(options))
    {
        writer.Database.ExecuteSqlRaw(
            "UPDATE \"Products\" SET \"Name\" = 'Database name' WHERE \"Id\" = 1");
    }
    
    var second = db.Products.Single(p => p.Id == 1);
    Console.WriteLine($"Same instance: {ReferenceEquals(first, second)}");
    Console.WriteLine($"After another query: {second.Name}");
    Console.WriteLine($"Original name: {db.Entry(first).Property(p => p.Name).OriginalValue}");
    
    db.Entry(first).Reload();
    Console.WriteLine($"After Reload: {first.Name}");
    Console.WriteLine($"Original after Reload: {db.Entry(first).Property(p => p.Name).OriginalValue}");
    
    public sealed class IdentityContext : DbContext
    {
        public IdentityContext(DbContextOptions<IdentityContext> options) : base(options) { }
        public DbSet<IdentityProduct> Products => Set<IdentityProduct>();
    }
    
    public sealed class IdentityProduct
    {
        public int Id { get; set; }
        public string Name { get; set; } = "";
    }
    Output
    info: 12/01/2026 10:51:33.226 RelationalEventId.CommandExecuted[20101] (Microsoft.EntityFrameworkCore.Database.Command)
          Executed DbCommand (0ms) [Parameters=[], CommandType='Text', CommandTimeout='30']
          SELECT "p"."Id", "p"."Name"
          FROM "Products" AS "p"
          WHERE "p"."Id" = 1
          LIMIT 2
    After query: Unchanged
    info: 12/01/2026 10:51:33.300 RelationalEventId.CommandExecuted[20101] (Microsoft.EntityFrameworkCore.Database.Command)
          Executed DbCommand (0ms) [Parameters=[], CommandType='Text', CommandTimeout='30']
          UPDATE "Products" SET "Name" = 'Database name' WHERE "Id" = 1
    info: 12/01/2026 10:51:33.303 RelationalEventId.CommandExecuted[20101] (Microsoft.EntityFrameworkCore.Database.Command)
          Executed DbCommand (0ms) [Parameters=[], CommandType='Text', CommandTimeout='30']
          SELECT "p"."Id", "p"."Name"
          FROM "Products" AS "p"
          WHERE "p"."Id" = 1
          LIMIT 2
    Same instance: True
    After another query: Pencil
    Original name: Pencil
    info: 12/01/2026 10:51:33.349 RelationalEventId.CommandExecuted[20101] (Microsoft.EntityFrameworkCore.Database.Command)
          Executed DbCommand (0ms) [Parameters=[@p='?' (DbType = Int32)], CommandType='Text', CommandTimeout='30']
          SELECT "p"."Id", "p"."Name"
          FROM "Products" AS "p"
          WHERE "p"."Id" = @p
          LIMIT 1
    After Reload: Database name
    Original after Reload: Database name

    Needs the package Microsoft.EntityFrameworkCore.Sqlite 10.0.12. Built and run with it: the output above is what the program really printed.

    The logs show both queries executing. Nevertheless, ReferenceEquals is True, and the name after the second query remains Pencil. The original name also remains Pencil: EF returned the tracked instance without overwriting its values.

    Reload deliberately refreshes the tracked instance. For the existing row in this example, both its current and original name become Database name. Reloading can overwrite unsaved edits, so use it intentionally.

    Attaching a second instance with the same key throws; updating data from an API shows the error and the fixes.

    The mistake to avoid. Another tracking query is not a refresh operation. It can execute SQL and still return the same object with its existing values.

    In an interview, say: “The identity map keeps one tracked instance per entity type and primary key. Another tracking query reuses it without refreshing its values. Reload deliberately refreshes it. Attaching another instance with the same key throws an InvalidOperationException saying another instance is already tracked. Reuse the tracked instance or copy the intended values onto it.”

    Continue with tracking modes and their costs for queries that do not need ordinary context tracking.

    Why does a growing change tracker cost more, and what does Clear do?

    Each tracked entity consumes memory for the instance and tracking information, including snapshots under the default strategy. A detection pass must examine tracked entities for changes. As the tracker grows, memory use and detection work grow too.

    Prefer a short-lived unit of work: one bounded operation that loads entities, changes them, saves, and finishes. Disposing its context is the normal way to end tracking. You can also explicitly detach one entity by setting its entry's state to Detached.

    ChangeTracker.Clear() stops tracking all entities. It is more efficient than detaching them one by one. For bounded batches, clearing after a successful save can release tracking information when those instances are no longer needed.

    Clearing before saving discards the pending work recorded by the tracker. It does not undo assignments already made to your objects, save anything, or roll back database work.

    Clearing is also not general failure recovery. An EF-thrown InvalidOperationException can leave the context unusable. Do not assume that clearing a context after a tracking conflict makes it safe to continue.

    The mistake to avoid. Clear is not “save and reset,” and it is not a database rollback. Pending tracked edits will no longer be saved through those entries.

    In an interview, say: “A long-lived context accumulates tracked entities and snapshots, increasing memory use and detection work. Prefer short units of work. Clear stops tracking everything and drops pending tracked changes; it neither saves nor rolls back. It also does not make an unusable context safe.”

    Context ownership and batching patterns belong in the DbContext lifetime lesson.

    Check yourself

    A product is tracked as Unchanged. You change only its Name through an ordinary property assignment, then call SaveChanges with default snapshot tracking and automatic detection enabled. What normally happens?

    A EF Core updates only Name; the entity is then Unchanged.
    B No UPDATE is sent unless you also call Update on the entity.
    C EF Core updates every column because the entity is tracked.
    D EF Core updates Name, then detaches the entity from the context.
    Show answer

    Correct answer: A

    SaveChanges normally detects ordinary property edits. The changed property is marked for updating, and successful default acceptance returns the entry to Unchanged.

    Your context tracks Product 1. Another operation changes that row in the database. You run another tracking LINQ query for Product 1. What should you expect?

    A SQL runs, but EF returns the tracked instance with its old values.
    B EF skips the SQL and returns the tracked instance from memory.
    C SQL runs, and EF tracks a second Product 1 instance with new values.
    D SQL runs, and EF overwrites the tracked instance with the new values.
    Show answer

    Correct answer: A

    A tracking query still executes against the database. Identity resolution reuses the tracked instance without overwriting its values. Reload is a deliberate refresh operation.

    Going deeper

    Connected entities and generated keys. A graph is a set of entity instances connected through navigation properties. Add, Attach and Update can traverse these connections, rather than affecting only the object passed to the method. With generated keys, Attach and Update can recognize an unset key as a new entity and mark it Added. Do not apply the simple “Attach means Unchanged” rule blindly to an entire mixed graph.

    Saving without accepting. SaveChanges(acceptAllChangesOnSuccess: false) separates database saving from acceptance of the tracking records. The default successful state transitions described earlier depend on acceptance. Calling ChangeTracker.AcceptAllChanges() performs that acceptance later; it does not execute the database writes again.

    Tracking boundaries. Direct SQL, such as the update in the identity example, does not automatically synchronize already tracked instances. The same distinction matters for set-based operations covered in bulk updates and deletes.

    Sources

    Practice

    Practice test: Practice: Change Tracking: Entity States, Snapshots, DetectChanges and the Identity Map9 questions · 1 mark each, no negative markingFull Access
    Take the test
    Sign in to mark lessons done and keep your place in the course.Sign in

    Checked before publishing: links opened, reviewed while it was written and read in full. How lessons are checked

    Updated 1 Dec 2026 ·