EF Core Global Query Fix
In this tutorial, you'll learn about EF Core Global Query Fix. We cover key concepts, practical examples, and best practices.
Your EF Core query returns fewer rows than expected, a query that used to work now silently filters data, or an admin page shows incomplete results. A global query filter is likely the cause — it is applied invisibly to every query.
The Problem
// A global query filter was configured:
modelBuilder.Entity<Order>().HasQueryFilter(o => !o.IsDeleted);
// An admin query:
var allOrders = await db.Orders.ToListAsync();
// Returns only non-deleted orders — even for admin!
Output: Customers see only active orders (correct). But the admin panel also hides deleted orders (incorrect).
The Fix
var allOrders = await db.Orders
.IgnoreQueryFilters()
.ToListAsync();
IgnoreQueryFilters() bypasses all global query filters for that query. Use it for admin operations, reporting, and data maintenance.
For conditional filters based on the caller:
public class AppDbContext : DbContext
{
private readonly bool _isAdmin;
public AppDbContext(DbContextOptions<AppDbContext> options, IHttpContextAccessor http)
: base(options)
{
_isAdmin = http?.HttpContext?.User?.IsInRole("Admin") ?? false;
}
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<Order>().HasQueryFilter(o =>
_isAdmin || !o.IsDeleted);
}
}
Now admin users see all records without needing IgnoreQueryFilters.
Prevention
- Use
IgnoreQueryFilters()for queries that should see all data. - Use context-level parameters for role-based filter behavior.
- Log generated SQL to verify filters are applied as expected.
- Document all global query filters in the DbContext.
- Test queries with and without
IgnoreQueryFilters(). - Be aware that
IgnoreQueryFiltersapplies to all filters on that entity. - Use
IgnoreAutoIncludeif navigation property auto-include is the issue.
Common Mistakes with core global query fix
- Using
foldlinstead offoldl'causing stack overflow on large lists - Forgetting
deriving (Show, Eq)on custom data types needed for debugging - Placing the wildcard pattern first in case expressions, making all subsequent patterns unreachable
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
Learn more about EF Core query filters at DodaTech.
Built by the developers of DodaTech
Doda Browser, DodaZIP & Durga Antivirus Pro