-
Notifications
You must be signed in to change notification settings - Fork 226
Global Query Filters
Simon Hughes edited this page Aug 30, 2026
·
4 revisions
EF Core's global query filters allow you to define query predicates that are automatically applied to all queries for an entity type. Common use cases include soft-deletes and multi-tenancy.
The generated DbContext is public but not partial by default, and the OnModelCreatingPartial hook is
only emitted for a partial class. So make it partial first.
In Database.tt:
Settings.DbContextClassModifiers = "public partial";The generator then emits a call to OnModelCreatingPartial inside OnModelCreating, along with
InitializePartial, DisposePartial and OnCreateModelPartial:
// Generated code (do not edit)
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
// ... generated configuration ...
OnModelCreatingPartial(modelBuilder);
}
partial void OnModelCreatingPartial(ModelBuilder modelBuilder);Create a new file (e.g., MyDbContext.Filters.cs) with your partial class implementation. This file is not overwritten by the generator.
// MyDbContext.Filters.cs — hand-written, not generated
namespace MyProject.Data;
public partial class MyDbContext
{
partial void OnModelCreatingPartial(ModelBuilder modelBuilder)
{
// Soft-delete filter: automatically exclude deleted records
modelBuilder.Entity<Order>().HasQueryFilter(p => !p.IsDeleted);
// Multi-tenant filter: only return records for the current tenant
modelBuilder.Entity<Customer>().HasQueryFilter(c => c.TenantId == _currentTenantId);
// Combine filters
modelBuilder.Entity<Product>().HasQueryFilter(p => p.IsActive && !p.IsDeleted);
}
// Inject tenant context via constructor or property
private readonly int _currentTenantId;
}Global filters can be disabled for individual queries using .IgnoreQueryFilters():
// Include soft-deleted records for an admin view
var allOrders = dbContext.Orders.IgnoreQueryFilters().ToList();- Settings A-Z - every setting, with a page each
- Common Settings Types Explained
- Settings Callbacks
- Settings runtime values and helpers
- Filtering
- Full Control Over the Generated Code
- Enum Generation from Table Data
- Owned Entities
- JSON column support
- Global Query Filters
- Extended Property Names Feature
- Partial Properties
- File-Scoped Namespaces
- Data Annotations
- Spatial Types
- HierarchyId
- RowVersion and TimeStamp columns
- Lazy Loading
- Stored proc result sets
- Custom File-Based Templates
- Extra entities via partial classes
- INotifyPropertyChanged
- Syntax colour for T4