In EF Core 10, what do a DbContext and its DbSet<T> properties do, and when does a change actually reach the database?
answer
- a session, not a connection
- DbSet<T> is an IQueryable<T> root
- Add only marks the entry Added
- SaveChangesAsync returns Task<int>
- Find checks the change tracker first
basics
~20 sA DbContext is EF Core's session with a database: it owns the model, tracks entities and turns their changes into SQL. Each DbSet<T> is the query root for one entity type. Nothing is written until SaveChanges or SaveChangesAsync runs.
solid answer
~40 sA `DbContext` is a short-lived session: it carries the model, the change tracker and the connection handling for one unit of work. Each `DbSet<TEntity>` property is an `IQueryable<TEntity>` root, so a LINQ query on it is translated to SQL and runs only when you enumerate it, for example with `ToListAsync()`. `Add`, `Remove` and setting properties on tracked entities only change tracker state; `SaveChangesAsync()` then detects changes, sends the `INSERT`, `UPDATE` and `DELETE` statements, and returns the number of entries written. `Find` returns an already-tracked entity without a query. The context is not thread-safe and should be disposed after the unit of work.
code
csharp · 16 linespublic class NewsContext(DbContextOptions<NewsContext> options) : DbContext(options)
{
public DbSet<Article> Articles => Set<Article>();
}
// one unit of work
var article = new Article { Title = "Budget passes", Published = false };
context.Articles.Add(article); // tracked as Added, no SQL yet
var drafts = await context.Articles
.Where(a => !a.Published)
.ToListAsync(); // SELECT runs here
foreach (var draft in drafts) draft.Published = true;
int written = await context.SaveChangesAsync(); // INSERT + UPDATEs run herego deeper
Recall that the context is a session and each DbSet<T> a query root, and that writes happen only in SaveChanges or SaveChangesAsync.
Explain deferred execution on DbSet<T>, which calls cause a round trip, and how Find uses the change tracker before querying.
Show the lifetime consequences: a short-lived, single-threaded context, disposal, and why a context that threw InvalidOperationException is discarded rather than reused.
Discuss how the session model shapes service boundaries: one SaveChanges per unit of work, and where batching or explicit transactions are worth the added complexity.
## What a DbContext is A **`DbContext`** is the class you derive from to talk to a database with EF Core. One instance represents a **session** with that database, used for a single unit of work and then disposed. It is not a database connection: EF opens a connection just before each operation and closes it right afterwards, and the ADO.NET driver pools the physical connections underneath. During that session the context holds three things: - the **model**: EF's metadata describing every entity type, its table, columns and keys; - the **change tracker**: a record of every entity the context has loaded or been told about, with a state such as `Added`, `Unchanged`, `Modified` or `Deleted`; - the **database facade** (`context.Database`): connection, transaction and raw-SQL access. In a news API the context might look like `public class NewsContext(DbContextOptions<NewsContext> options) : DbContext(options)` with a `DbSet<Article> Articles` property. ## DbSet<T>: query root and entry point A **`DbSet<TEntity>`** represents the set of all entities of one type. It is an abstract class that implements **`IQueryable<TEntity>`**, so: - `context.Articles.Where(a => a.Published)` builds an expression tree and sends **no SQL** yet; - the SQL runs when the query is **enumerated**: `ToListAsync()`, `FirstOrDefaultAsync()`, `CountAsync()`, a `foreach`; - `Add`, `AddRange`, `Attach`, `Update` and `Remove` put an entity into the change tracker with a state; - `Find` / `FindAsync` look up by primary key and return an entity the context already tracks **without a round trip**, querying only when it is not tracked; - `Local` exposes the tracked entities of that type. EF fills every `DbSet<T>` property that has a setter when the context is constructed, which is why the properties can be declared without initialisers. `context.Set<TEntity>()` gives the same set without a property. ## When SQL actually goes out | Operation | Database round trip? | |---|---| | `context.Articles.Where(...)` | No: it only composes a query | | `await query.ToListAsync()` | Yes: a `SELECT` | | `context.Articles.Add(article)` | No: the entry becomes `Added` | | `article.Title = "Updated"` on a tracked entity | No: detected later | | `await context.SaveChangesAsync()` | Yes: the `INSERT` / `UPDATE` / `DELETE` statements | | `await context.Articles.FindAsync(id)` | Only if `id` is not tracked yet | `SaveChanges()` returns an `int` and `SaveChangesAsync()` a `Task<int>`: the number of state entries written. It detects changes on tracked entities first, then sends the statements inside a transaction when more than one is needed. One exception to "Add sends nothing": `AddAsync` exists for special value generators such as SQL Server's HiLo sequence strategy, which may need the database to hand out key values. With ordinary identity keys, including the Npgsql provider's default identity columns, `Add` is enough. ## Where the context gets its configuration A context needs **options** before it can do anything: a provider and connection, set with `UseNpgsql`, `UseSqlServer` or `UseSqlite` on a `DbContextOptionsBuilder`, either passed into the constructor as `DbContextOptions<TContext>` or applied in an `OnConfiguring` override. It also needs a **model**, which EF builds the first time a context type is used and then caches for that type. That caching is why creating a new context per unit of work is cheap: a new instance reuses the cached model and the provider's internal services instead of rebuilding them, and the database connection itself comes from the driver's pool only when an operation runs. ## A typical unit of work 1. Get a context instance: injected per request, or from a factory. 2. Query or attach the entities you need; they become tracked. 3. Change them, add new ones or remove old ones. 4. Call `SaveChangesAsync()` once. 5. Dispose the context, or let the dependency-injection scope do it. ## Lifetime rules that follow from this design - A context is **cheap to create** and meant to be **short-lived**. A long-lived one keeps growing its change tracker and serves stale tracked data. - A context is **not thread-safe**: run one operation at a time and `await` each call before the next. - An `InvalidOperationException` thrown by EF can leave the context in an unrecoverable state; discard the instance instead of reusing it. - **Dispose** it after use so its services and event hooks are released. ## Mistakes interviewers listen for - Saying EF writes as soon as a property is set: the write happens in `SaveChanges`. - Treating a `DbSet<T>` as an in-memory list: every enumeration re-queries the database. - Calling `SaveChangesAsync()` inside a loop for each row when one call at the end would batch the work. - Keeping one context for the application's whole life.
- What does DbSet<T>.FindAsync do differently from FirstOrDefaultAsync(a => a.Id == id)?`FindAsync` checks the change tracker first and returns an already-tracked entity with that primary key without a database round trip; it queries only on a miss. `FirstOrDefaultAsync` always sends a `SELECT`, though for a tracking query EF still returns the tracked instance. `FindAsync` works only by primary key, while `FirstOrDefaultAsync` accepts any predicate.
- Why does AddAsync exist if Add sends no SQL?`AddAsync` exists for value generators that may need the database while the entity is being added, such as SQL Server's HiLo sequence strategy fetching a new block of keys. For identity columns and client-side GUIDs, nothing needs the database at add time, so the synchronous `Add` is the normal call.
- EF Core writes to the database as soon as a tracked property is set.
- A DbContext holds one open database connection for its whole lifetime.
- A DbSet<T> is an in-memory list loaded when the context starts.
- One DbContext instance can serve the whole application as a singleton.
- ChangeTracker.DetectChanges() sends the pending UPDATE statements.