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.
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).
"The Entry API is how I talk to the change tracker about one specific entity.
db.Entry(order)gives me anEntityEntry<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 setIsModifiedmyself, 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
RowVersionit read, I set it as the property'sOriginalValue, not its current value, because EF Core uses original values in theWHEREclause. Then a stale write affects zero rows and I getDbUpdateConcurrencyException. In the catch block, the exception's entries give meGetDatabaseValuesAsync(), so I can show the user what changed or decide to merge. For related data,Collection(o => o.Lines).LoadAsync()loads a navigation explicitly, andCollection(...).Query()gives me anIQueryableover 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,
TrackGraphis the precise tool.AttachandUpdateapply one rule to the whole graph based on whether the key is set.TrackGraphcalls 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()triggersDetectChangeseach time, so it becomes quadratic. I use it for precise, local control, and let normal tracking do the rest."
| 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 TrackGraphAttach/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 |
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.
Checks practical fluency with the Entry API: values, property flags, explicit loading and graph tracking, and knowing their traps.
Green flags
RowVersion as the original value and explains why.IsModified for partial updates rather than State = Modified.Collection(...).Query() to count or filter children in SQL.TrackGraph gives over Attach/Update.Red flags
SetValues with request DTOs that contain non-editable fields.Entry() triggers DetectChanges.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.
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
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.
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.
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.
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.
OriginalValue and CurrentValue for it.IsModified on one property and log the UPDATE.RowVersion as the original value, save, catch DbUpdateConcurrencyException and print GetDatabaseValuesAsync().Collection(...).Query().CountAsync() and compare its SQL with LoadAsync().TrackGraph callback for a graph with client-generated Guid keys using an IsNew flag on the DTO.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;
}
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.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.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.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.Collection(...).Query().CountAsync() or AnyAsync().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.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.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 |
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.
EF Core does not load navigation properties unless you ask. There are three ways:
Include(o => o.Lines).ThenInclude(l => l.Product) loads related data in the same query (LEFT JOINs), or in several with AsSplitQuery().await db.Entry(order).Collection(o => o.Lines).LoadAsync() loads one navigation later, on demand; .Query() lets you filter or count instead.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.
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:
ChangeTracker.Clear() or use a new context per chunk.AsNoTracking() or projections.AutoDetectChangesEnabled around bulk Add loops and call DetectChanges once.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.
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.
Last updated 23 Nov 2026.