What are global query filters in EF Core?

Entity Framework & EF Core Modelling Intermediate 2–3 Yrs3–5 Yrs Conceptual 1 min read

Quick Answer

A global query filter is a WHERE predicate EF Core automatically appends to every query for an entity type. Configure it in OnModelCreating with HasQueryFilter. The classic uses are soft delete (e => !e.IsDeleted) and multi-tenancy (e => e.TenantId == _currentTenant).

A global query filter is a condition EF Core adds to every query for an entity automatically. I set it up in OnModelCreating with HasQueryFilter. The two things I use it for constantly are soft delete — o => !o.IsDeleted so deleted rows just vanish from normal queries — and multi-tenancy, where the filter compares a TenantId against the current user's tenant that the context holds. If I need to see the filtered-out rows, like an admin restore page, I call IgnoreQueryFilters. The main gotcha is that the filter also applies through Include, so a filtered-out parent hides its children.

  • modelBuilder.Entity<Order>().HasQueryFilter(o => !o.IsDeleted); — every db.Orders query now excludes soft-deleted rows without you writing the filter each time.
  • For per-tenant filtering, capture a field the context reads (set from the current user) — the filter closes over it.
  • Bypass it with db.Orders.IgnoreQueryFilters() — e.g. an admin “restore deleted” screen.
  • Gotchas: the filter also applies to Included navigations (a filtered parent hides its children); required relationships between filtered and unfiltered entities can produce warnings; one filter per entity type (combine conditions with &&).