skip to content

Context Options & Pooling

The DbContext and its options: DbContextOptionsBuilder with UseSqlServer, UseNpgsql or UseSqlite, one context per unit of work, and pooling. Interviewers ask why a shared context breaks under load.

part ofEntity Framework Coreread it →
on this pageshow

explore

questions

5

In EF Core 10, what do a DbContext and its DbSet<T> properties do, and when does a change actually reach the database?

level: juniorimportance: must knowfreq 74%

answer

  1. a session, not a connection
  2. DbSet<T> is an IQueryable<T> root
  3. Add only marks the entry Added
  4. SaveChangesAsync returns Task<int>
  5. Find checks the change tracker first

basics

~20 s

A 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 s

A `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 lines
csharp
public 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 here

go deeper

for a junior

Recall that the context is a session and each DbSet<T> a query root, and that writes happen only in SaveChanges or SaveChangesAsync.

for a middle

Explain deferred execution on DbSet<T>, which calls cause a round trip, and how Find uses the change tracker before querying.

for a senior

Show the lifetime consequences: a short-lived, single-threaded context, disposal, and why a context that threw InvalidOperationException is discarded rather than reused.

for a principal

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.
open as a page

In EF Core, why does one DbContext shared by concurrent work fail under load, and what does EF throw when it detects the overlap?

level: middleimportance: must knowfreq 66%

basics

~20 s

A DbContext is not thread-safe: its change tracker, connection and transaction state assume one operation at a time. When a second operation starts before the first completes, EF throws InvalidOperationException; when the overlap goes undetected, results and tracked state can be corrupted.

open as a page

In EF Core, how does configuring a DbContext in OnConfiguring differ from passing DbContextOptions<TContext> to its constructor, and can the two be combined?

level: middleimportance: should knowfreq 44%

basics

~20 s

Constructor options are built outside the context, by DI or a DbContextOptionsBuilder<TContext>, and passed in; OnConfiguring builds them inside the class. OnConfiguring still runs when options were passed, so the two combine, and IsConfigured tells it a provider is already set.

open as a page

In EF Core, when should code take an IDbContextFactory<TContext> instead of an injected context, and what does AddPooledDbContextFactory register and change?

level: seniorimportance: should knowfreq 36%

basics

~20 s

Take IDbContextFactory<TContext> when the code's lifetime does not match one context: singletons, background jobs, parallel branches, long-lived UI sessions. The caller creates and disposes each context. AddPooledDbContextFactory backs the factory with a context pool and also registers a scoped TContext.

open as a page

In EF Core 10, what does AddDbContextPool reuse, what does its poolSize of 1024 actually limit, and what does returning a context to the pool reset?

level: seniorimportance: should knowfreq 40%

basics

~20 s

AddDbContextPool reuses DbContext instances to skip their setup cost. poolSize, 1024 by default, caps how many idle instances are kept, not concurrency. On return EF clears tracking, transactions and owned connections and restores startup settings, but not your own fields.

open as a page