LyraLearn AI Learning Platform
Exams
← Module 4 Β· EF Core and Data Scenarios
🎧 Listen

Tracking and DbContext Lifetime

Two deceptively simple questions expose whether you actually understand EF Core or just use it: "What does AsNoTracking do?" and "Why is my entity not saving?" Both are really questions about the change tracker and the DbContext lifetime, and interviewers love them because the confident-but-wrong answers are so common.

The change tracker in one breath

When a query materializes entities, the context takes a snapshot of each one. On SaveChanges(), EF diffs current values against the snapshot and generates UPDATE statements for what changed. That's the whole mechanism. From it, everything else follows:

A strong answer to "why is my entity not saving?" enumerates the causes aloud: the entity came from an AsNoTracking query, it was loaded by a different context instance than the one calling SaveChanges(), or SaveChanges() was never reached because of an early return or swallowed exception. Then: "I'd check context.Entry(entity).State in the debugger." Naming the diagnostic step is what separates the levels.

Context-per-request and the lifetime pitfalls

AddDbContext registers the context as scoped β€” one instance per HTTP request. Know why: DbContext is cheap to create, not thread-safe, and its unit-of-work semantics map naturally to one request. Then know the two classic pitfalls:

Answers that fall flat

Practice prompts

🧠 Quiz yourself on this lesson →

Ask the AI Tutor

Grounded in the course lessons β€” it cites its sources and says when it doesn't know.