.NET Developer interview question
How does Entity Framework change tracking work?
EF Core tracks entity identity, original values, and state in a DbContext, then generates updates on SaveChanges. Use short-lived contexts and AsNoTracking for read-only queries to reduce memory and surprises.
Direct answer
What a strong answer covers
How it works
A DbContext keeps an identity map of every entity it has loaded or attached, together with its original property values and a state of Unchanged, Modified, Added, or Deleted. When SaveChanges runs, the tracker compares current values against originals and generates UPDATE statements only for changed columns, wrapped in one transaction. Tracking costs memory and time proportional to the number of entities, so read-only queries use AsNoTracking, contexts are short-lived per unit of work, and bulk operations use ExecuteUpdate or ExecuteDelete instead of loading rows to change them.
Example
A report endpoint that loaded 50,000 orders took seconds and hundreds of megabytes until the query added AsNoTracking, after which it ran in a fraction of the time. In the same service, updating an order’s status loads the entity, sets one property, and calls SaveChanges, which issues an UPDATE for that single column and detects a concurrency conflict through the row version.
Common mistakes
- Keeping one DbContext alive for the application lifetime and accumulating every entity ever loaded.
- Loading a million rows to update a flag instead of using ExecuteUpdate.
- Attaching a detached entity as Modified and overwriting every column including ones another user changed.
A useful answer structure
Answer from your own work.
Do not memorise a script: use only examples you can explain honestly in follow-up questions.
Open the desktop workspace and rehearse a clear answer in your own words.