Shared-schema multi-tenancy in EF Core 10: TenantId columns, a named global query filter, a scoped tenant provider, stamping inserts, and the leaks caused by IgnoreQueryFilters, pooling and jobs without a request.
In a shared schema every tenant-owned table gets a TenantId column, and the DbContext declares a global query filter such as e => e.TenantId == TenantId, where TenantId is a property on the context. EF Core treats that member as a parameter, so each query adds WHERE TenantId = @__TenantId. A scoped tenant provider sets it from a validated claim, and a SaveChanges interceptor stamps it on inserts.
The risks are the gaps around the filter: IgnoreQueryFilters(), raw SQL, ExecuteUpdate, pooled contexts keeping the last tenant, and background jobs with no request. The trade-off: one filter gives cheap, convenient isolation, but it is a single line of defence, so high-stakes systems add row-level security in SQL Server as well.
"With a shared schema, isolation is a
WHERE TenantId = @tenanton every query, and the point of the EF Core design is that nobody has to remember to write it. I add aTenantIdto every tenant-owned entity, usually through anITenantOwnedinterface, and inOnModelCreatingI apply a query filter that compares it with a property on theDbContext. That detail matters: because the filter references a context member, EF Core caches one query plan and passes the tenant as a parameter. If you closed over a local variable instead, you would capture one tenant for the life of the model, which is a data leak.The tenant itself comes from a scoped
ITenantProviderthat reads a claim from the validated token, never from a header the client controls. Inserts get the tenant from aSaveChangesInterceptor, which also refuses to save an entity whose tenant doesn't match. For example, at [company] we ran [about 300] tenants in one Azure SQL database, and I added an integration test that ran every repository method as tenant A against data seeded for tenant B and asserted that nothing came back. It caught [two] raw SQL queries that had bypassed the filter.The mistake I see is believing the filter covers everything. It doesn't apply to
FromSqlRawwithout composition,ExecuteSql,ExecuteUpdateon unfiltered sets or anything afterIgnoreQueryFilters(), which before EF Core 10 also removed the soft-delete filter and the tenant filter together. Pooling and background jobs are the other two holes. I treat the filter as convenience and back it with tests and, for sensitive data, SQL Server row-level security."
| Part | Responsibility |
|---|---|
ITenantOwned + TenantId column |
Marks tenant data, indexed as the leading key |
ITenantProvider (scoped) |
Resolves the tenant from a validated claim |
| Global query filter | Adds WHERE TenantId = @p to every query |
SaveChangesInterceptor |
Stamps TenantId on inserts, blocks cross-tenant writes |
| Tests | Prove tenant A never sees tenant B's data |
| Gap | Why | Mitigation |
|---|---|---|
IgnoreQueryFilters() |
Removes filters | EF Core 10 named filters; ignore only SoftDelete |
FromSql / SqlQuery / ExecuteSql |
Raw SQL you wrote | Add the tenant predicate; review and test |
ExecuteUpdate / ExecuteDelete |
Filters apply to the source query, but easy to misuse via unfiltered sets | Always start from the filtered DbSet |
| Pooled contexts | Context reused across requests | Set the tenant on every lease |
| Background jobs | No HttpContext |
Pass the tenant id in the message; fail closed |
In a [SaaS rostering platform with 300 tenants on one Azure SQL database], adding TenantId as the leading key column to the [six] busiest indexes cut p95 query time from [180 ms to 25 ms], and the cross-tenant test suite of [400] cases ran in CI on every pull request.
Checks whether the candidate can implement shared-schema tenancy correctly and knows exactly where EF Core's filter stops protecting them.
Green flags
DbContext member in the filter and explains parameterisationIgnoreQueryFilters, raw SQL, pooling and background jobs as gapsRed flags
TenantIdHasQueryFilter(e => e.TenantId == this.TenantId)
│ EF Core sees a reference to the DbContext instance
▼
Compiled query (cached once per model):
SELECT ... FROM Orders o WHERE o.TenantId = @__ef_filter__TenantId
│ at execution, EF reads this.TenantId from the current context
▼
Parameter value differs per context instance
EF Core special-cases members of the DbContext in filters: it extracts them as parameters at execution time. A captured local or a static field is evaluated once when the model is built and frozen into the cached model, so every tenant would see the first tenant's data.
Before EF Core 10 an entity had only one filter, so tenant and soft delete were combined with &&, and IgnoreQueryFilters() removed both. EF Core 10 adds named filters:
modelBuilder.Entity<Order>()
.HasQueryFilter("Tenant", o => o.TenantId == TenantId)
.HasQueryFilter("SoftDelete", o => !o.IsDeleted);
db.Orders.IgnoreQueryFilters(["SoftDelete"]); // tenant filter still applies
HTTP request → JWT validated → claim "tid" → ITenantProvider (scoped) → DbContext.TenantId
Never trust X-Tenant-Id from the client by itself. If tenants are chosen by subdomain, map the host to a tenant and check the user belongs to it.
AddDbContextPool reuses context instances. EF Core resets its own state (tracker, options) but not your fields. Two safe patterns:
AddPooledDbContextFactory and a scoped wrapper factory that leases a context and sets TenantId every time.A hosted service has no request scope. Create a scope, set the tenant from the message or job argument, and have the provider throw when no tenant is set. An unset tenant must mean "no rows", or better an exception, never "all rows".
Every query now filters on TenantId, so it should lead the composite keys of the hottest indexes: (TenantId, CreatedAt), (TenantId, CustomerId). A unique email per tenant is (TenantId, Email).
SQL Server row-level security (a security predicate function using SESSION_CONTEXT(N'TenantId'), set by a connection interceptor) enforces the same rule inside the database, covering raw SQL and other tools. It costs a little CPU and complicates admin queries.
ToQueryString().AddDbContextPool, forget to reset the tenant, and write a test that exposes the leak.IgnoreQueryFilters(["SoftDelete"]) keeps tenant isolation.A tenant provider, a named query filter, and an interceptor that stamps and checks the tenant on save:
namespace Rostering.Infrastructure;
using System.Security.Claims;
using Microsoft.AspNetCore.Http;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Diagnostics;
public interface ITenantOwned { Guid TenantId { get; set; } }
public interface ITenantProvider { Guid TenantId { get; } }
// Scoped: one per request. Fails closed when no tenant is present.
public sealed class ClaimsTenantProvider(IHttpContextAccessor accessor) : ITenantProvider
{
public Guid TenantId =>
Guid.TryParse(accessor.HttpContext?.User.FindFirstValue("tid"), out var id)
? id
: throw new InvalidOperationException("No tenant for this operation.");
}
public sealed class Shift : ITenantOwned
{
public Guid Id { get; init; } = Guid.CreateVersion7();
public Guid TenantId { get; set; }
public required string Role { get; set; }
public DateTimeOffset StartsAt { get; set; }
}
public sealed class RosterDbContext(DbContextOptions<RosterDbContext> options, ITenantProvider tenant)
: DbContext(options)
{
// A DbContext member: EF Core reads it per query and sends it as a parameter.
public Guid TenantId => tenant.TenantId;
public DbSet<Shift> Shifts => Set<Shift>();
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<Shift>(b =>
{
b.HasQueryFilter("Tenant", s => s.TenantId == TenantId); // EF Core 10 named filter
b.HasIndex(s => new { s.TenantId, s.StartsAt }); // tenant leads the index
});
}
}
public sealed class TenantStampInterceptor(ITenantProvider tenant) : SaveChangesInterceptor
{
public override ValueTask<InterceptionResult<int>> SavingChangesAsync(
DbContextEventData eventData, InterceptionResult<int> result, CancellationToken ct = default)
{
foreach (var entry in eventData.Context!.ChangeTracker.Entries<ITenantOwned>())
{
if (entry.State == EntityState.Added)
entry.Entity.TenantId = tenant.TenantId;
else if (entry.State is EntityState.Modified or EntityState.Deleted
&& entry.Entity.TenantId != tenant.TenantId)
throw new InvalidOperationException("Cross-tenant write blocked.");
}
return base.SavingChangesAsync(eventData, result, ct);
}
}
// Program.cs: no pooling, so the scoped provider and interceptor are fresh per request.
builder.Services.AddHttpContextAccessor();
builder.Services.AddScoped<ITenantProvider, ClaimsTenantProvider>();
builder.Services.AddScoped<TenantStampInterceptor>();
builder.Services.AddDbContext<RosterDbContext>((sp, options) => options
.UseSqlServer(builder.Configuration.GetConnectionString("Roster"))
.AddInterceptors(sp.GetRequiredService<TenantStampInterceptor>()));
The SQL EF Core sends for db.Shifts.Where(s => s.StartsAt >= from):
SELECT [s].[Id], [s].[Role], [s].[StartsAt], [s].[TenantId]
FROM [Shifts] AS [s]
WHERE [s].[TenantId] = @ef_filter__TenantId AND [s].[StartsAt] >= @from
DbContext.IgnoreQueryFilters() to show deleted rows. Why it is wrong: Before EF Core 10 it also removes the tenant filter. Instead: Use EF Core 10 named filters and ignore only SoftDelete.ExecuteSql or uncomposed raw SQL. Instead: Add the predicate, or compose LINQ over FromSql so the filter applies, and test it.AddDbContextPool with tenant state in fields. Why it is wrong: A pooled instance keeps the previous request's tenant. Instead: Avoid pooling or set the tenant on every lease.TenantId out of indexes. Why it is wrong: Every query filters on it, so scans grow with the number of tenants. Instead: Make it the leading key of the hot indexes.A global filter is a convenience, not a security boundary. I want three layers for tenant isolation: the EF Core filter so normal code is correct by default, automated cross-tenant tests so mistakes are caught in CI, and, where the data is sensitive or contractual isolation is promised, SQL Server row-level security so the database enforces it even for raw SQL and reporting tools.
Under the Privacy Act 1988, one tenant seeing another's personal information is likely a notifiable data breach. That makes the cost of the extra layers easy to justify for anything holding personal data.
| Option | When it fits | Cost | When not to |
|---|---|---|---|
| EF Core filter only | Low-sensitivity data, small team | Cheapest | Personal or financial data |
| Filter + cross-tenant tests | Most SaaS apps | Test suite upkeep | — |
| Filter + SQL Server RLS | Sensitive data, contractual isolation | Some CPU, harder admin queries | Prototypes |
| Database per tenant | Strong isolation, per-tenant restore | Operations and cost | Thousands of tiny tenants |
A global query filter is a predicate configured with HasQueryFilter that EF Core adds to every LINQ query for that entity type: direct queries, Includes, navigation loads, Find and even ExecuteUpdate/ExecuteDelete. Typical uses are soft delete (!IsDeleted) and multi-tenancy (TenantId == _tenantId). Per-request values must come from a DbContext member so EF parameterises them per context instance. IgnoreQueryFilters() turns filters off for one query, and EF Core 10 named filters let you define several and ignore just one (IgnoreQueryFilters(["SoftDelete"])). The big pitfall: a required navigation to a filtered entity becomes an INNER JOIN, so dependants vanish silently. The trade-off is safety by default versus hidden behaviour that surprises people and needs matching indexes.
DbContext pooling keeps a pool of context instances and hands one out per scope instead of constructing a new one, saving the setup cost and allocations of each context. AddDbContextPool<T>() registers a scoped lease; AddPooledDbContextFactory<T>() registers a singleton factory for background work. When a lease ends, EF Core resets its own state: the change tracker, tracking options, the current transaction. It does not reset your fields, so a TenantId property set in one request can leak into the next. Pooled contexts must have a single constructor taking DbContextOptions and can't inject scoped services. For per-request values I wrap the pooled factory in a scoped factory that sets them on every lease. The trade-off: the gain is real but small per request, worth it at high throughput, and it adds a class of state bugs.
The EF filter keeps normal code tenant-scoped automatically, so handlers stay simple and nobody forgets a Where. Row-level security enforces the same rule in the database: create a security policy with an inline predicate function comparing TenantId to SESSION_CONTEXT(N'TenantId') (plus a block predicate to stop cross-tenant writes), and set the session context from a DbConnectionInterceptor when each connection opens, with @read_only = 1. Together they're defence in depth: raw SQL, IgnoreQueryFilters or a bug still can't read another tenant's rows. Costs: the predicate runs on every query, so TenantId must lead the relevant indexes or RLS can turn seeks into scans on large tables; debugging is harder because rows silently disappear; and the session context must be set on every connection open because of pooling.
How to tell it (STAR)
**S:** At [company] we ran [300] tenants in one Azure SQL database with an EF Core tenant filter. **T:** A customer reported unfamiliar names in an export, and I [led the investigation]. **A:** I reproduced it with two tenants and found the export used raw SQL that EF Core could not compose over, so the filter never applied. I switched the endpoint off, worked with our privacy officer on the breach assessment, rewrote the query, and added cross-tenant tests for every endpoint plus row-level security in the database. **R:** [N] tenants were affected for [a few hours]; since then the test suite has caught [several] unsafe queries before merge.
Last updated 23 Nov 2026.