Covers EF Core global query filters: HasQueryFilter, how filters are added to every LINQ query (including Include, Find and ExecuteUpdate), parameterising them through DbContext members, IgnoreQueryFilters, EF Core 10 named filters, the required-navigation INNER JOIN pitfall (warning 10622), one filter per hierarchy root and indexing for filtered columns.
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.
"A global query filter is a LINQ predicate attached to an entity type in the model. When EF Core compiles any query that touches that type, it adds the predicate as a
WHEREclause: for the root, for everyInclude, for lazy and explicit loads, forFindand forExecuteUpdateandExecuteDeletetoo. It's the standard way to make soft-deleted rows disappear, and to scope rows to a tenant, without every developer remembering aWhere.The detail that matters is where per-request values come from. The model is built once and cached, so if the filter captured a local variable during
OnModelCreating, that value is frozen for the life of the app. EF Core special-cases members of theDbContext: if the filter references_tenantIdon the context, EF turns it into a parameter and reads it from the current context instance on each query. So the tenant id is injected into the context's constructor and the filter uses that field. To bypass filters, you callIgnoreQueryFilters(). Before EF Core 10 that was all or nothing, and you could only have one filter per entity: callingHasQueryFiltertwice replaced the first, which caught a lot of people. EF Core 10 added named filters, so I can defineSoftDeleteandTenantseparately and have an admin 'recycle bin' query ignore onlySoftDeletewhile staying tenant-scoped.The pitfall I always mention is required navigations. If
Orderhas a filter andOrderLinehas a required navigation toOrder, thenInclude(l => l.Order)becomes an INNER JOIN with the filter applied, and lines whose order is soft-deleted silently disappear from results. EF logs warning 10622 for this. The fix is to make the relationship optional or apply a matching filter to the dependant. The mistake I see is treating filters as a security boundary on their own. They're a strong default, but oneIgnoreQueryFiltersor raw SQL call goes around them, so for tenant isolation I add database row-level security or tests behind them."
| Operation | Filter applied? |
|---|---|
db.Orders.Where(...) |
Yes |
Include / ThenInclude |
Yes, on the included set |
| Lazy and explicit loading | Yes |
Find / FindAsync |
Yes (after checking the tracker) |
ExecuteUpdate / ExecuteDelete |
Yes |
FromSql(...) composed with LINQ |
Yes, added around the raw SQL |
Database.ExecuteSql / SqlQuery |
No |
| Already-tracked entities | Not re-checked |
| EF Core 9 and earlier | EF Core 10 | |
|---|---|---|
| Filters per entity | One (combine with &&) |
Many, by name |
| Bypass | IgnoreQueryFilters() (all) |
IgnoreQueryFilters() or IgnoreQueryFilters(["Name"]) |
After moving soft delete into a named filter and adding a filtered index WHERE IsDeleted = 0 on (CustomerId, CreatedAt), the orders list query dropped from [480 ms] to [35 ms] p95 on [12M] rows, and the admin recycle bin could ignore SoftDelete without losing the tenant filter.
Checks practical knowledge of global query filters and the traps that cause data leaks or missing rows.
Green flags
DbContext members.Red flags
OnModelCreating.IgnoreQueryFilters() casually in admin queries.modelBuilder.Entity<Order>().HasQueryFilter(o => !o.IsDeleted && o.TenantId == _tenantId);
var recent = await db.Orders.Where(o => o.CreatedAt > since).ToListAsync(ct);
SELECT [o].[Id], [o].[CreatedAt], [o].[IsDeleted], [o].[TenantId], ...
FROM [Orders] AS [o]
WHERE [o].[IsDeleted] = CAST(0 AS bit)
AND [o].[TenantId] = @__ef_filter___tenantId_0
AND [o].[CreatedAt] > @__since_0
The @__ef_filter__ parameter is read from the current DbContext instance at execution time.
OnModelCreating runs once -> model cached (keyed by context type)
filter: o => o.TenantId == localVar localVar evaluated once -> constant in model (BUG)
filter: o => o.TenantId == this._tenantId EF rewrites to a parameter bound per context (OK)
This is also why the tenant id must be set before the first query on a context, and why pooled contexts must reset it (implement IResettableService or set it from a factory per lease).
modelBuilder.Entity<Order>()
.HasQueryFilter("SoftDelete", o => !o.IsDeleted)
.HasQueryFilter("Tenant", o => o.TenantId == _tenantId);
var deleted = await db.Orders.IgnoreQueryFilters(["SoftDelete"]).Where(o => o.IsDeleted).ToListAsync(ct);
OrderLine --(required)--> Order [filter: !IsDeleted]
db.OrderLines.Include(l => l.Order)
-> INNER JOIN (SELECT ... FROM Orders WHERE IsDeleted = 0) o ON l.OrderId = o.Id
-> lines of deleted orders are dropped from the result, not just their Order
EF Core logs CoreEventId.PossibleIncorrectRequiredNavigationWithQueryFilterInteractionWarning (10622). Fixes: give OrderLine its own matching filter (!l.Order.IsDeleted, which is what you usually want), or make the navigation optional so EF uses a LEFT JOIN.
Filters can only be defined on the root entity type of a hierarchy. For TPH, use EF.Property<string>(e, "Discriminator") or type checks in the root filter if derived types need different rules.
Every query now has the filter's predicate. Without support it can turn seeks into scans:
CREATE INDEX IX_Orders_Customer_Created ON Orders (TenantId, CustomerId, CreatedAt)
WHERE IsDeleted = 0; -- filtered index matches the soft-delete filter
In EF Core: HasIndex(o => new { o.TenantId, o.CustomerId, o.CreatedAt }).HasFilter("[IsDeleted] = 0"). Filtered indexes need the predicate to match literally, and parameterised plans sometimes can't use them; check the plan.
ToQueryString() on a query with Include, and find the filter in both parts.A pool-safe tenant and soft-delete setup with EF Core 10 named filters.
namespace Shop.Data;
using Microsoft.EntityFrameworkCore;
public interface ITenantContext { Guid TenantId { get; } }
public sealed class ShopDbContext(DbContextOptions<ShopDbContext> options, ITenantContext tenant) : DbContext(options)
{
// A DbContext member: EF parameterises it per context instance. A captured local would be frozen.
private Guid TenantId => tenant.TenantId;
public DbSet<Order> Orders => Set<Order>();
public DbSet<OrderLine> OrderLines => Set<OrderLine>();
protected override void OnModelCreating(ModelBuilder b)
{
b.Entity<Order>()
.HasQueryFilter("SoftDelete", o => !o.IsDeleted)
.HasQueryFilter("Tenant", o => o.TenantId == TenantId);
// Matching filter on the dependant avoids the silent INNER JOIN drop (warning 10622).
b.Entity<OrderLine>()
.HasQueryFilter("SoftDelete", l => !l.Order.IsDeleted)
.HasQueryFilter("Tenant", l => l.Order.TenantId == TenantId);
// Support the filter in the index.
b.Entity<Order>()
.HasIndex(o => new { o.TenantId, o.CustomerId, o.CreatedAt })
.HasFilter("[IsDeleted] = 0");
}
}
// Recycle bin: still tenant-scoped, only SoftDelete is ignored.
app.MapGet("/admin/orders/deleted", (ShopDbContext db, CancellationToken ct) =>
db.Orders.IgnoreQueryFilters(["SoftDelete"])
.Where(o => o.IsDeleted)
.Select(o => new { o.Id, o.DeletedAt })
.ToListAsync(ct));
OnModelCreating for the filter. Why it is wrong: the model is cached, so the first value is used forever and every tenant sees the first tenant's rows. Instead: reference a DbContext field or property.HasQueryFilter twice on EF Core 9 or earlier. Why it is wrong: those versions keep one filter per entity type, so the second call replaces the first, silently dropping soft delete or tenancy. Instead: combine with &&, or use named filters on EF Core 10.IgnoreQueryFilters() for an admin query when only soft delete should be bypassed, while tenancy is also enforced by a global filter on the same entity. Why it is wrong: the parameterless call removes every filter on the query, so the tenant predicate goes too and other tenants' rows come back. Instead: named filters and IgnoreQueryFilters(["SoftDelete"]), or an explicit tenant Where on that query, plus a test that asserts no cross-tenant rows.IgnoreQueryFilters and other tools bypass them. Instead: add SQL Server row-level security or isolation tests.TenantId and use filtered indexes for soft delete.Global filters are a good default and a poor guarantee. For soft delete I'm happy to rely on them; for tenant isolation, where a leak is a notifiable data breach under the Privacy Act, I want defence in depth: the EF filter for ergonomics, SQL Server row-level security keyed on SESSION_CONTEXT as the real boundary, and integration tests that query as tenant A and assert nothing from tenant B comes back, including through Include paths.
The EF Core 10 named filters remove the most common workaround, a single combined filter plus IgnoreQueryFilters sprinkled through admin code, which used to drop tenancy along with soft delete. I check filter cost with ToQueryString() and the actual execution plan, because a filtered index that doesn't match the parameterised predicate quietly stops being used.
| Option | When it fits | Cost | When not to |
|---|---|---|---|
| Global filter | Soft delete, tenant scoping, 'active' rows | Hidden predicate on every query | As the only security boundary |
Explicit Where / specification |
Rules that vary by use case | Must remember it | Cross-cutting rules everyone needs |
| SQL Server row-level security | Hard tenant isolation | Predicate function on every query, harder debugging | Single-tenant apps |
| Separate database per tenant | Strong isolation, noisy neighbours | Operations, migrations at scale | Thousands of tiny tenants |
Interceptors let you run code before and after EF Core operations without touching every call site. The main ones are DbCommandInterceptor (see or change the SQL, time it, or suppress execution and return a cached result), SaveChangesInterceptor (inspect the ChangeTracker in SavingChangesAsync to set audit columns, turn deletes into soft deletes or write outbox rows), and DbConnectionInterceptor (run code as a connection opens, such as setting SESSION_CONTEXT for row-level security). You register them with AddInterceptors, usually resolved from DI. With AddDbContextPool they behave like singletons, so they must not capture scoped services. They don't see everything: ExecuteUpdate/ExecuteDelete bypass SaveChanges interceptors. The trade-off is central, invisible behaviour versus surprise for anyone reading a handler, so keep them few, fast and documented.
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], finance noticed our monthly line-item export was about [3%] short against the ledger after we'd added soft delete to orders. **T:** I was asked to find where the rows had gone. **A:** I compared the generated SQL before and after the release and saw that including the order from each line had become an inner join to the filtered orders, so lines of deleted orders vanished. EF had even logged warning 10622, but we weren't alerting on it. I fixed the report, added explicit filters on the dependant entities, and made that warning throw in our test suite. **R:** The export reconciled to the cent the next month, and the test has caught [N] similar relationships since.
Last updated 23 Nov 2026.