EF Core Global Query Filter
In this tutorial, you'll learn about EF Core Global Query Filter. We cover key concepts, practical examples, and best practices.
Every query to your Orders table must include WHERE IsDeleted = 0. You add this condition to every LINQ query manually. One developer forgets, and soft-deleted records appear in the UI. Global query filters apply automatically to all queries for an entity.
Wrong
var activeOrders = await db.Orders
.Where(o => !o.IsDeleted) // Manual filter — easy to forget
.ToListAsync();
var recentOrders = await db.Orders
.Where(o => o.Date > cutoff)
// Forgot the IsDeleted filter!
.ToListAsync();
Output: recentOrders includes soft-deleted records. Inconsistent filtering.
Right
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<Order>().HasQueryFilter(o => !o.IsDeleted);
}
Now every query automatically includes WHERE IsDeleted = 0:
var orders = await db.Orders.Where(o => o.Date > cutoff).ToListAsync();
// Generated SQL: SELECT * FROM Orders WHERE Date > @cutoff AND IsDeleted = 0
Filters apply to all LINQ queries including Include, navigation properties, and Count.
Disable for specific queries:
var allOrders = await db.Orders
.IgnoreQueryFilters()
.ToListAsync(); // Includes deleted
Prevention
- Use
HasQueryFilterinOnModelCreatingfor multi-tenancy, soft-delete, and row-level security. - Use
IgnoreQueryFilters()for admin queries that need to bypass the filter. - Combine multiple conditions with
&&in a single filter. - Use filters with
HasValueGeneratorfor automatic tenant ID assignment. - Test queries with filters enabled — unexpected filters can cause performance issues.
- Document each filter clearly — they affect all queries invisibly.
Common Mistakes with core global query filter
- Misunderstanding that
Stringis[Char]with poor performance for large text operations - Using
foldlinstead offoldl'causing stack overflow on large lists - Forgetting
deriving (Show, Eq)on custom data types needed for debugging
These mistakes appear frequently in real-world EF code. DodaTech's contributors have identified these patterns through analysis of open-source projects and production systems.
Practice Exercise
Write a pure function that safely divides two integers using Maybe, then test it with edge cases like division by zero and negative numbers.
This exercise reinforces the concepts covered in this guide. Try implementing it before checking online solutions.
FAQ
Global query filters power multi-tenancy in DodaTech's SaaS applications. For more EF Core, visit DodaTech.
Built by the developers of DodaTech
Doda Browser, DodaZIP & Durga Antivirus Pro