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

📚 Interview question

How do you use the EF Core Entry API? Show how to read original and current values, check or set IsModified on a property, load a collection or reference explicitly, and use TrackGraph to set states on a disconnected graph.

Covers the EF Core Entry API in code: EntityEntry state, CurrentValues, OriginalValues and GetDatabaseValuesAsync, PropertyEntry.IsModified and OriginalValue (including RowVersion), CollectionEntry and ReferenceEntry loading and Query(), CurrentValues.SetValues, ReloadAsync, and ChangeTracker.TrackGraph for disconnected graphs.

Mid-Level Coding Intermediate change-tracking concurrency ef-core entry-api explicit-loading trackgraph

🎯 Key points

  • db.Entry(entity) returns EntityEntry<T>: State, CurrentValues, OriginalValues, GetDatabaseValuesAsync()
  • Property(p).IsModified / CurrentValue / OriginalValue for one property; set OriginalValue of RowVersion for concurrency
  • CurrentValues.SetValues(source) copies properties whose names match the entity (others are ignored); only values that differ are flagged modified
  • Collection(c).LoadAsync() / Reference(r).LoadAsync() for explicit loading; IsLoaded; Query() to filter or count without loading
  • On DbUpdateConcurrencyException: ex.Entries + GetDatabaseValuesAsync() to choose client wins, database wins or merge
  • ChangeTracker.TrackGraph(root, callback) decides a state per node; returns per-node control unlike Attach/Update
  • Entry() calls DetectChanges, so avoid it in tight loops over many tracked entities
  • ReloadAsync() refreshes from the database and discards local changes

⏱ 30-second answer

db.Entry(entity) returns an EntityEntry<T>, the change tracker's view of one entity:

  • State, CurrentValues, OriginalValues and GetDatabaseValuesAsync() for state and values.
  • Property(p => p.X) gives CurrentValue, OriginalValue and IsModified, so you can mark one column for update, or set the RowVersion original value for a concurrency check.
  • Collection(...)/Reference(...) give explicit loading (LoadAsync, IsLoaded) and Query() to filter or count related rows without loading them all.
  • CurrentValues.SetValues(dto) copies matching values; ReloadAsync() discards local changes.

For disconnected graphs, ChangeTracker.TrackGraph visits each node so you choose its state. The trade-off: it gives precise control, but it is easy to misuse (setting current instead of original values, or calling Entry() in hot loops).

🗣 Full answer (senior)

How I would answer this in an interview

"The Entry API is how I talk to the change tracker about one specific entity. db.Entry(order) gives me an EntityEntry<Order> with its state, the current values, the original values from the snapshot, and a way to fetch the database values right now. At property level, Entry(order).Property(o => o.Status) tells me whether that property is modified and lets me set IsModified myself, which is how I do a one-column update on an attached stub without reading the row first.

The use I rely on most is concurrency. If my client sends back the RowVersion it read, I set it as the property's OriginalValue, not its current value, because EF Core uses original values in the WHERE clause. Then a stale write affects zero rows and I get DbUpdateConcurrencyException. In the catch block, the exception's entries give me GetDatabaseValuesAsync(), so I can show the user what changed or decide to merge. For related data, Collection(o => o.Lines).LoadAsync() loads a navigation explicitly, and Collection(...).Query() gives me an IQueryable over the related rows so I can count or filter them in SQL, which is great on an aggregate with thousands of children.

For disconnected graphs, TrackGraph is the precise tool. Attach and Update apply one rule to the whole graph based on whether the key is set. TrackGraph calls my callback for each entity, so I can say this order is Modified, these lines with an id are Unchanged, this one with a zero id is Added. The mistake I see is using the Entry API inside loops over thousands of entities: Entry() triggers DetectChanges each time, so it becomes quadratic. I use it for precise, local control, and let normal tracking do the rest."


The main members

Member Returns / does Typical use
Entry(e).State EntityState (get/set) Check or force a state
Entry(e).CurrentValues / OriginalValues PropertyValues Inspect, copy, SetValues(dto)
Entry(e).GetDatabaseValuesAsync() PropertyValues? from a fresh query Concurrency conflict resolution
Entry(e).ReloadAsync() Overwrites current and original with database values Discard local changes
Property(p).IsModified bool (get/set) Partial updates on attached stubs
Property(p).OriginalValue value (get/set) RowVersion from the client
Collection(c).LoadAsync() / IsLoaded Explicit loading Load children on demand
Collection(c).Query() IQueryable<TChild> Count or filter children in SQL
Reference(r).LoadAsync() Explicit loading Load a parent on demand
ChangeTracker.TrackGraph(root, cb) Visits every reachable node Per-node state on disconnected graphs

Attach/Update vs TrackGraph

Attach/Update TrackGraph
Rule One rule for all nodes, based on key set Your callback per node
Client-generated keys Can't tell new from existing You decide (for example a DTO flag or version)
Stops traversal No Yes: leave a node Detached and its children aren't visited

Production example

An order screen showed "N lines" by loading every line of [~5,000-line] wholesale orders; switching to Entry(order).Collection(o => o.Lines).Query().CountAsync() turned a [~4 MB, 600 ms] load into a [~2 ms] COUNT.

🔍 What the interviewer is checking

Checks practical fluency with the Entry API: values, property flags, explicit loading and graph tracking, and knowing their traps.

Green flags

  • Sets RowVersion as the original value and explains why.
  • Uses IsModified for partial updates rather than State = Modified.
  • Uses Collection(...).Query() to count or filter children in SQL.
  • Explains what TrackGraph gives over Attach/Update.

Red flags

  • Sets concurrency tokens as current values.
  • Uses SetValues with request DTOs that contain non-editable fields.
  • Unaware that Entry() triggers DetectChanges.

📚 Learn in depth

1. What an EntityEntry wraps

EntityEntry<Order>  (public, cheap wrapper)
  └ InternalEntityEntry  (the real tracker record)
       ├ State
       ├ original values snapshot
       ├ modified flags per property
       └ relationship snapshot

Calling db.Entry(e) on an untracked object returns an entry in the Detached state; it doesn't start tracking until you set a state.

2. Original vs current vs database values

original  = snapshot at load/attach (or what you set)
current   = what the object holds now
database  = what the row holds now (GetDatabaseValuesAsync runs a query)

An UPDATE sets current values for modified properties and uses original values of concurrency tokens in the WHERE clause:

UPDATE [Orders] SET [Notes] = @p0
OUTPUT INSERTED.[RowVersion]
WHERE [Id] = @p1 AND [RowVersion] = @p2;   -- @p2 is the ORIGINAL RowVersion

3. SetValues

Entry(e).CurrentValues.SetValues(source) copies every property whose name matches from a DTO, dictionary or another entity. Only values that differ become modified, so it's a neat way to apply an edit without writing every column. It also means any matching property is copied, so the source must be a DTO with only editable fields.

4. Explicit loading and Query()

await db.Entry(order).Collection(o => o.Lines).LoadAsync(ct);
SELECT [o].[Id], [o].[OrderId], [o].[ProductId], [o].[Quantity]
FROM [OrderLines] AS [o]
WHERE [o].[OrderId] = @p

Query() exposes the same query for composition: .Where(l => l.Quantity > 10).ToListAsync() loads only those lines (and still fixes them up into order.Lines if tracked), and .CountAsync() loads nothing.

5. TrackGraph

TrackGraph(root, node => ...)
  visit root -> callback sets state
  for each navigation of a node now tracked:
       visit child if not already tracked -> callback
  nodes left Detached: their children are not visited

node.Entry is the entity's entry; node.SourceEntry and node.InboundNavigation tell you how you got there.

6. Cost

Entry() and ChangeTracker.Entries() call DetectChanges first (when auto-detect is on). Inside a loop of 10,000 tracked entities that is 10,000 full scans.

Try it yourself

  1. Load an order, change a property, and print OriginalValue and CurrentValue for it.
  2. Attach a stub, set IsModified on one property and log the UPDATE.
  3. Set a stale RowVersion as the original value, save, catch DbUpdateConcurrencyException and print GetDatabaseValuesAsync().
  4. Use Collection(...).Query().CountAsync() and compare its SQL with LoadAsync().
  5. Write a TrackGraph callback for a graph with client-generated Guid keys using an IsNew flag on the DTO.

💻 Code

Common Entry API tasks in one service.

namespace Shop.Orders;

using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.ChangeTracking;

public sealed record EditOrderRequest(string? Notes, DateOnly DeliverOn, byte[] RowVersion);

public sealed class OrderEntryExamples(ShopDbContext db)
{
    // 1. Apply an edit with a concurrency check; only changed columns are written.
    public async Task EditAsync(int id, EditOrderRequest req, CancellationToken ct)
    {
        var order = await db.Orders.SingleAsync(o => o.Id == id, ct);
        var entry = db.Entry(order);

        entry.Property(o => o.RowVersion).OriginalValue = req.RowVersion; // goes in WHERE
        entry.CurrentValues.SetValues(new { req.Notes, req.DeliverOn });  // only editable fields

        foreach (var p in entry.Properties.Where(p => p.IsModified))
            Console.WriteLine($"{p.Metadata.Name}: {p.OriginalValue} -> {p.CurrentValue}");

        try
        {
            await db.SaveChangesAsync(ct);
        }
        catch (DbUpdateConcurrencyException ex)
        {
            var conflict = ex.Entries.Single();
            var dbValues = await conflict.GetDatabaseValuesAsync(ct);   // null if the row was deleted
            throw new OrderConflictException(id, dbValues?.ToObject() as Order);
        }
    }

    // 2. One-column update without a read.
    public Task MarkPrintedAsync(int id, CancellationToken ct)
    {
        var stub = new Order { Id = id, IsPrinted = true };
        db.Attach(stub);                                            // Unchanged
        db.Entry(stub).Property(o => o.IsPrinted).IsModified = true;
        return db.SaveChangesAsync(ct);                             // UPDATE [Orders] SET [IsPrinted] = @p0 WHERE [Id] = @p1
    }

    // 3. Explicit loading and counting children in SQL.
    public async Task<int> CountBigLinesAsync(Order order, CancellationToken ct)
    {
        var lines = db.Entry(order).Collection(o => o.Lines);
        if (!lines.IsLoaded)
            return await lines.Query().CountAsync(l => l.Quantity >= 100, ct);  // SELECT COUNT(*) ...
        return order.Lines.Count(l => l.Quantity >= 100);
    }

    // 4. Disconnected graph with client-generated keys: decide each node's state.
    public Task SaveGraphAsync(Order order, IReadOnlySet<Guid> newLineIds, CancellationToken ct)
    {
        db.ChangeTracker.TrackGraph(order, node =>
        {
            node.Entry.State = node.Entry.Entity switch
            {
                Order => EntityState.Modified,
                OrderLine line when newLineIds.Contains(line.PublicId) => EntityState.Added,
                OrderLine => EntityState.Unchanged,
                _ => EntityState.Unchanged,          // e.g. referenced Product: never update it
            };
        });
        return db.SaveChangesAsync(ct);
    }
}

public sealed class OrderConflictException(int id, Order? current)
    : Exception($"Order {id} was changed by someone else.")
{
    public Order? Current { get; } = current;
}

⚠ Common mistakes

  • Mistake: Setting the client's RowVersion with CurrentValue (or assigning the property). Why it is wrong: the WHERE clause uses the original value, which is still the freshly loaded version, so the check always passes. Instead: set Property(p => p.RowVersion).OriginalValue.
  • Mistake: Calling CurrentValues.SetValues(requestDto) with a DTO that has extra properties. Why it is wrong: every matching property is copied, so clients can over-post fields like CreditLimit. Instead: pass a DTO or anonymous object with only editable fields.
  • Mistake: Setting Entry(e).State = Modified to save a partial change. Why it is wrong: it marks every property modified and writes every column. Instead: set IsModified on the specific properties, or let DetectChanges find them.
  • Mistake: Calling db.Entry(x) inside a loop over thousands of tracked entities. Why it is wrong: each call runs DetectChanges, so the loop is quadratic. Instead: call ChangeTracker.Entries() once, or turn off auto-detect for the loop.
  • Mistake: Loading a whole collection just to count or check it. Why it is wrong: it materialises and tracks every child. Instead: Collection(...).Query().CountAsync() or AnyAsync().
  • Mistake: Using Update() on a graph with client-generated keys. Why it is wrong: every node has a key, so new children become Modified and the UPDATE affects zero rows, causing a concurrency exception. Instead: TrackGraph with an explicit rule for new vs existing.
  • Mistake: Using ReloadAsync() as a general refresh. Why it is wrong: it silently discards local changes and costs a query per entity. Instead: use it deliberately, for example in conflict handling.

🏛 Senior insight: trade-offs

The Entry API is the scalpel; normal tracking is the default tool. I reach for it in three places: concurrency (original RowVersion and database values on conflict), precise partial updates, and related-data queries via Query(). TrackGraph is worth knowing because it's the honest answer to "how do you save a disconnected graph with client-generated keys", though I usually prefer to load the aggregate and reconcile, which is easier to read and test. For high-volume work I keep the Entry API out of loops entirely: one ChangeTracker.Entries() call, or ExecuteUpdate when no per-entity logic is needed.

Option When it fits Cost When not to
Property(...).OriginalValue Concurrency across a disconnect None —
IsModified on a stub Hot one-column updates Must know the key and what changed When validation needs current state
Collection(...).Query() Large child collections Separate query Small collections already loaded
TrackGraph Disconnected graphs, client keys Callback logic to maintain When loading and reconciling is simpler

Resolving a concurrency conflict with the entry from DbUpdateConcurrencyException.Entries:

Strategy How When it fits
Database wins entry.ReloadAsync() and tell the user Most user-facing edits: return 409 and let them retry
Client wins entry.OriginalValues.SetValues(await entry.GetDatabaseValuesAsync()), save again The caller is authoritative (rare)
Merge Compare original, current and database values per property; keep non-conflicting edits Different users routinely edit different fields

🔗 Follow-ups the interviewer may ask

  1. When: Candidate mentions TrackGraph or attaching stubs. Why: Checks the wider choice between Add, Attach, Update and load-and-apply.
    How to answer

    All three walk the whole graph and set states based on whether each entity has a key value:

    • Add: everything becomes Added, so EF Core inserts it.
    • Attach: entities with a key become Unchanged, without one become Added. Nothing is written until you change something.
    • Update: entities with a key become Modified with every property marked, because EF Core has no original values to compare with, so it writes every column.

    That makes Update dangerous for APIs: it overwrites columns the client never meant to change and silently loses concurrent edits. Better: accept a use-case DTO containing only the editable fields (so nothing can be over-posted), load the entity tracked and apply the DTO so only real changes are written, use Attach plus IsModified for a known partial update, or ExecuteUpdate for set-based changes, always with a RowVersion set as the original value. The trade-off is one extra read in exchange for correct, minimal updates.

  2. When: Candidate mentions explicit loading. Why: Checks the trade-offs between eager, explicit and lazy loading.
    How to answer

    EF Core does not load navigation properties unless you ask. There are three ways:

    • Eager loading: Include(o => o.Lines).ThenInclude(l => l.Product) loads related data in the same query (LEFT JOINs), or in several with AsSplitQuery().
    • Explicit loading: await db.Entry(order).Collection(o => o.Lines).LoadAsync() loads one navigation later, on demand; .Query() lets you filter or count instead.
    • Lazy loading: with UseLazyLoadingProxies() and virtual navigations, the first access runs a query automatically.

    Filtered Include (EF Core 5+) lets you write Include(c => c.Orders.Where(o => o.IsOpen).OrderBy(o => o.PlacedAt).Take(5)).

    The trade-off: eager is predictable, explicit is precise, lazy is convenient but hides N+1 queries.

  3. When: Candidate mentions that Entry() calls DetectChanges. Why: Checks change tracker performance at scale.
    How to answer

    Every tracked entity costs an entry, an identity-map slot and an original-values snapshot, and DetectChanges scans all of them on every SaveChanges (and on Entries()/Entry()). On one long-lived context the tracked set keeps growing, so each save gets slower and the total becomes roughly quadratic, while memory climbs until the job runs out.

    The fixes:

    • Chunk: save every few hundred to few thousand entities, then ChangeTracker.Clear() or use a new context per chunk.
    • Read with AsNoTracking() or projections.
    • Turn off AutoDetectChangesEnabled around bulk Add loops and call DetectChanges once.
    • For set-based changes, skip the tracker with ExecuteUpdate/ExecuteDelete, or SqlBulkCopy for millions of inserts.

    The trade-off: chunking gives up all-or-nothing atomicity, and bypassing the tracker skips interceptors and domain logic.

🛠 Real-world problems: how you handle them

Order screen loading thousands of lines just to show a count
Situation
A [wholesale ordering] portal on Azure SQL; some customers' orders have [~5,000] lines. The order summary endpoint loaded the order, then explicitly loaded all lines to show a count and a 'large quantity' badge.
Signals
p95 latency on `GET /orders/{id}/summary` of [~600 ms] for large customers; Application Insights dependency calls returning [~4 MB]; memory spikes on the API instances during month-end ordering.
Investigation
Application Insights end-to-end transaction showed one `SELECT ... FROM [OrderLines] WHERE [OrderId] = @p` returning thousands of rows. `LogTo` confirmed `Collection(o => o.Lines).LoadAsync()` followed by in-memory `Count()`. `ToQueryString()` on the alternative query showed a single `COUNT`.
Resolution
Replaced the load with `Entry(order).Collection(o => o.Lines).Query().CountAsync(...)` for the badge and count, and changed the endpoint to load the order no-tracking. Later moved the summary to a DTO projection with subquery counts.
Prevention
A performance test with a [5,000-line] order in the integration suite; a review guideline: never load a collection only to count it; an Application Insights alert on dependency response size for that endpoint.

How to tell it (STAR)

**S:** At [company], our order summary page was slow for [our biggest wholesale customers], around [600 ms] at p95. **T:** I picked up the ticket to find out why. **A:** In Application Insights I saw each request pulling thousands of order lines, about [4 MB], just to show a count and a badge. I replaced the explicit load with `Collection(...).Query().CountAsync()` so SQL Server did the counting, and loaded the order without tracking. **R:** p95 dropped to [~40 ms] for those customers and API memory during month-end stayed flat.

↩ Usually asked after

More in Change Tracking

Last updated 23 Nov 2026.

🌐 Sangam's Webring

⏪ Previous 🏠 Main Next ⏩
💬 Chat with me