📁 Sangam Dhakal - Portfolio v2.0 - Netscape Navigator 4.0
_
□
×

📚 Interview question

What are global query filters in EF Core? Explain how they are applied to queries, how per-request values such as a tenant id get into them, how IgnoreQueryFilters and the named filters added in EF Core 10 work, and the pitfalls with required navigations and indexes.

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.

Mid-Level Theory Intermediate ef-core ef-core-10 global-query-filters multi-tenancy soft-delete sql-server

🎯 Key points

  • HasQueryFilter adds a predicate to every LINQ query for that entity type, including Include, navigation loads, Find and ExecuteUpdate/ExecuteDelete
  • Per-request values must come from a DbContext member (field or property) so EF parameterises them; a captured local is baked into the cached model
  • IgnoreQueryFilters() turns off every filter on the query; EF Core 10 named filters allow IgnoreQueryFilters(["SoftDelete"]) for just one
  • EF Core 9 and earlier allow one (unnamed) filter per entity type: rules are combined with && in one predicate, and a second HasQueryFilter call replaces the first
  • Filters go on the root of an inheritance hierarchy
  • Required navigation to a filtered entity becomes an INNER JOIN, so dependants silently disappear (warning 10622): make it optional or filter both
  • Filters don't apply to raw ExecuteSql or to SQL outside EF; FromSql is filtered when composed
  • Every query gains the predicate: lead indexes with TenantId, use filtered indexes (WHERE IsDeleted = 0) and check the plan on large tables

⏱ 30-second answer

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.

🗣 Full answer (senior)

How I would answer this in an interview

"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 WHERE clause: for the root, for every Include, for lazy and explicit loads, for Find and for ExecuteUpdate and ExecuteDelete too. It's the standard way to make soft-deleted rows disappear, and to scope rows to a tenant, without every developer remembering a Where.

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 the DbContext: if the filter references _tenantId on 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 call IgnoreQueryFilters(). Before EF Core 10 that was all or nothing, and you could only have one filter per entity: calling HasQueryFilter twice replaced the first, which caught a lot of people. EF Core 10 added named filters, so I can define SoftDelete and Tenant separately and have an admin 'recycle bin' query ignore only SoftDelete while staying tenant-scoped.

The pitfall I always mention is required navigations. If Order has a filter and OrderLine has a required navigation to Order, then Include(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 one IgnoreQueryFilters or raw SQL call goes around them, so for tenant isolation I add database row-level security or tests behind them."


Where filters apply

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

Before and after EF Core 10

EF Core 9 and earlier EF Core 10
Filters per entity One (combine with &&) Many, by name
Bypass IgnoreQueryFilters() (all) IgnoreQueryFilters() or IgnoreQueryFilters(["Name"])

Production example

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.

🔍 What the interviewer is checking

Checks practical knowledge of global query filters and the traps that cause data leaks or missing rows.

Green flags

  • Explains that per-request values must be DbContext members.
  • Knows the required-navigation INNER JOIN problem.
  • Knows named filters in EF Core 10 and the old one-filter limit.
  • Treats filters as defaults, with RLS or tests for tenant isolation.

Red flags

  • Captures the tenant id in OnModelCreating.
  • Uses IgnoreQueryFilters() casually in admin queries.
  • Believes filters also protect raw SQL.

📚 Learn in depth

1. How a filter becomes SQL

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.

2. Why DbContext members are special

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).

3. Named filters (EF Core 10)

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);

4. The required navigation pitfall

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.

5. Inheritance

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.

6. Indexes

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.

Try it yourself

  1. Add a soft-delete filter, run ToQueryString() on a query with Include, and find the filter in both parts.
  2. Write a filter that captures a local variable, change the variable, and watch the query ignore the change.
  3. Reproduce warning 10622 with a required navigation and count the missing rows.
  4. On EF Core 10, define two named filters and ignore one.
  5. Compare plans with and without a filtered index on 1M rows with 10% deleted.

💻 Code

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));

⚠ Common mistakes

  • Mistake: Capturing a local variable or a service value in 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.
  • Mistake: Calling 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.
  • Mistake: Required navigation from a dependant to a filtered principal. Why it is wrong: the INNER JOIN removes dependants from results. Instead: add a matching filter to the dependant or make the relationship optional.
  • Mistake: Using 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.
  • Mistake: Treating filters as the only tenant isolation. Why it is wrong: raw SQL, IgnoreQueryFilters and other tools bypass them. Instead: add SQL Server row-level security or isolation tests.
  • Mistake: Adding filters without index support. Why it is wrong: every query gains a predicate that may force scans on large tables. Instead: lead indexes with TenantId and use filtered indexes for soft delete.
  • Mistake: Expecting already-tracked entities to be filtered. Why it is wrong: filters apply to queries, not to entities already in the change tracker. Instead: use a fresh context or clear the tracker after soft deletes.

🏛 Senior insight: trade-offs

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

🔗 Follow-ups the interviewer may ask

  1. When: Candidate mentions soft delete through an interceptor. Why: Checks how soft delete writes pair with the read-side filter.
    How to answer

    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.

  2. When: Candidate mentions multi-tenancy or data leaks. Why: Checks defence in depth for tenant isolation.
    How to answer

    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.

🛠 Real-world problems: how you handle them

Order lines disappearing from invoices after soft delete was added
Situation
An [invoicing] service on Azure SQL with [~2M] orders. A sprint added a soft-delete filter on `Order`. `OrderLine` had a required navigation to `Order`.
Signals
Finance reported monthly line-item exports with [~3%] fewer rows than the ledger; no errors; EF Core logs at Warning level contained event 10622, which nobody was watching.
Investigation
Compared the export query's `ToQueryString()` before and after the release: the `Include(l => l.Order)` had become an INNER JOIN to a filtered subquery. Counted lines whose order was soft-deleted: they matched the missing rows. Found warning 10622 in Application Insights traces.
Resolution
Immediately: the export used `IgnoreQueryFilters()` for that report, after confirming with finance that deleted orders' lines belonged in the ledger export. Then: added an explicit matching filter on `OrderLine`, reviewed every required navigation to filtered entities, and changed the finance export to state its intent explicitly.
Prevention
Configured `ConfigureWarnings(w => w.Throw(CoreEventId.PossibleIncorrectRequiredNavigationWithQueryFilterInteractionWarning))` in tests; a reconciliation test comparing export counts with a raw SQL count; an ADR on where soft-deleted rows must still appear.

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.

↩ Usually asked after

More in Advanced EF Core

Last updated 23 Nov 2026.

🌐 Sangam's Webring

⏪ Previous 🏠 Main Next ⏩
💬 Chat with me