In this lesson, you will learn how to automate data filtering across your entire application by applying Global Query Filters in Entity Framework Core.
The Concept of Global Query Filters
As your application grows, you often encounter requirements that apply to almost every database query. Two classic examples are soft-deletes (hiding rows marked as "deleted" instead of removing them) and multi-tenancy (ensuring a user only sees data belonging to their specific organization).
Instead of manually adding .Where(x => !x.IsDeleted) or .Where(x => x.TenantId == currentId) to every single LINQ query, EF Core allows you to define these rules once in your DbContext. Once configured, EF Core automatically injects these predicates into every query executed against those entities, even when using navigation properties or eager loading.
Implementing the Logic
To implement this, you override the OnModelCreating method in your DbContext. Here is how you would configure a soft-delete mechanism:
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
// Apply a global filter to the Product entity
modelBuilder.Entity<Product>().HasQueryFilter(p => !p.IsDeleted);
}
By defining this filter, any call like context.Products.ToList() will automatically be translated by the EF Core provider into a SQL query equivalent to SELECT * FROM Products WHERE IsDeleted = 0.
Important Considerations
- Performance: Because these filters are translated to SQL, they are efficient. However, ensure that columns used in your filters (like
IsDeletedorTenantId) are indexed to maintain high query performance. - Bypassing Filters: Occasionally, you might need to view "deleted" items (e.g., in an admin dashboard). You can bypass these global rules by using the
.IgnoreQueryFilters()operator on yourIQueryable:var allProducts = context.Products.IgnoreQueryFilters().ToList();
By centralizing these rules, you reduce boilerplate code and eliminate the risk of developers forgetting to filter sensitive data in new features.
Key Takeaway: Global Query Filters enforce business rules like multi-tenancy or soft-deletes at the model level, ensuring consistent data isolation across your entire application without manual intervention.