skip to content

In an EF Core 10 multi-tenant forum, why must a tenant query filter read a DbContext property rather than a value captured in OnModelCreating?

level: seniorimportance: should knowfreq 44%

answer

  1. OnModelCreating runs once per context type
  2. model is cached and shared
  3. context member becomes an ef_filter parameter
  4. captured local is frozen at first build
  5. pooled contexts must reset the value

basics

~20 s

OnModelCreating runs once and the model is cached, so a value captured there stays frozen for every later context. A filter reading a DbContext property, p => p.TenantId == TenantId, takes its value from the context running each query.

solid answer

~50 s

EF Core builds the model once per context type and caches it; `OnModelCreating` does not run again for the next request. If the filter captures a local or a service value — `var tenant = _tenantContext.TenantId; ...HasQueryFilter(p => p.TenantId == tenant)` — the first context's tenant is baked into the cached model and every later request sees that tenant's posts. EF treats references to the **context instance** specially: in `HasQueryFilter(p => p.TenantId == TenantId)`, where `TenantId` is a property of the `DbContext`, the funcletizer replaces the context with a parameter and reads the property from whichever context executes the query, sending it as a SQL parameter named with an `ef_filter` prefix. So I expose the tenant as a context property set from a scoped service in the constructor. With `AddDbContextPool` the constructor runs once per pooled instance, so the value must be set on every lease instead.

code

csharp · 6 lines
csharp
// Frozen: captured once, then reused by every context
var t = tenant.TenantId;
modelBuilder.Entity<Post>().HasQueryFilter(p => p.TenantId == t);

// Correct: read from the executing context on every query
modelBuilder.Entity<Post>().HasQueryFilter(p => p.TenantId == TenantId);

go deeper

for a junior

Know that a tenant filter compares the row's TenantId with a TenantId property on the DbContext.

for a middle

Explain why OnModelCreating runs once, why a captured local is frozen, and how a context property is turned into a per-query parameter.

for a senior

Spot captured values in filter code, handle IEntityTypeConfiguration and DbContext pooling, and prove isolation with two-tenant integration tests.

for a principal

Choose between a shared table with filters, a schema per tenant and a database per tenant, given isolation guarantees, cost and operational load.

## The setup The discussion forum stores every community's posts in one table with a `TenantId` column. Each request belongs to one tenant, resolved upstream from the host name or a claim and exposed through a scoped `ITenantContext` service. The query filter must restrict every query to that tenant. ## The bug: capturing a value in OnModelCreating ```csharp public class ForumDbContext(DbContextOptions<ForumDbContext> options, ITenantContext tenant) : DbContext(options) { protected override void OnModelCreating(ModelBuilder modelBuilder) { var tenantId = tenant.TenantId; // captured once modelBuilder.Entity<Post>().HasQueryFilter(p => p.TenantId == tenantId); // frozen } } ``` EF Core builds the **model** the first time a context of this type is used and **caches** it for the life of the process. `OnModelCreating` does not run for the next context. The lambda captured `tenantId` from the first instance, so every later context, for every tenant, filters by that first tenant's id. Depending on which request came first, users see another community's posts or none of their own. ## The fix: reference the context instance ```csharp public class ForumDbContext(DbContextOptions<ForumDbContext> options, ITenantContext tenant) : DbContext(options) { public Guid TenantId { get; } = tenant.TenantId; protected override void OnModelCreating(ModelBuilder modelBuilder) { modelBuilder.Entity<Post>().HasQueryFilter(p => p.TenantId == TenantId); } } ``` Here the filter refers to a **member of the context** (`this.TenantId`). When EF compiles a query, its expression funcletizer recognises any expression whose type is the context type and replaces it with a context parameter. The member access is then evaluated **per query, from the context that runs it**, and sent as a SQL parameter whose name starts with `ef_filter`. Two contexts for two tenants share the cached model and the compiled query, yet each sends its own tenant id. Rules that follow: 1. The filter may read **fields or properties of the context**; that includes a C# primary-constructor parameter, which the compiler stores in a field of the context. 2. It must not capture locals, static fields or service instances held outside the context. 3. An `IEntityTypeConfiguration<T>` has no context instance; the documented workaround is a never-assigned field of the context type in the configuration class that the filter references, which EF swaps for the executing context. ## DbContext pooling With `AddDbContextPool`, context instances are reused across requests and the constructor runs only when the pool creates an instance. A tenant id assigned in the constructor would therefore be stale on the next lease. Set it every time a context is handed out, for example through a factory that rents a pooled context and assigns the tenant before returning it, and make sure the value is reset when the context returns to the pool. ## What it looks like on the wire | Context instance | SQL sent | Parameter | |---|---|---| | Tenant A request | `WHERE p."TenantId" = @ef_filter__...` | A's id | | Tenant B request | same SQL text, same cached plan | B's id | The SQL text is identical, so the query cache and the database's plan cache are shared; only the parameter differs. ## Checks worth automating - An integration test that creates two contexts for two tenants and asserts each sees only its own posts. - A review rule: any `HasQueryFilter` referencing something other than the entity and the context is a finding.

  • How do you reference the tenant from a filter declared in an IEntityTypeConfiguration<Post> class?
    The configuration class has no context instance, so EF's docs show a workaround: declare a never-assigned field of your context type in the configuration class and write `p => p.TenantId == _context.TenantId`. Because the expression's type is the context type, EF replaces it with the executing context at query time.
  • Why does a tenant set in the DbContext constructor break with AddDbContextPool?
    A pooled instance is constructed once and then reused for many requests, so its constructor-assigned tenant stays whatever the first lease set. The tenant must be assigned on every lease, for example in a small factory that rents the context and sets the property, and cleared when the context returns to the pool.

  • OnModelCreating runs for every new DbContext instance.
  • A captured local in HasQueryFilter is re-read on each query.
  • Each tenant gets its own cached model automatically.
  • Tenant filters must be added manually to every query instead.
  • Constructor-set tenant values are safe with AddDbContextPool.