Advertisement
Advanced .NET, Entity Framework Core & Data Access

How do you implement soft deletes in EF Core using a global query filter?

Short answer

A global query filter (HasQueryFilter in OnModelCreating) automatically applies a WHERE condition (like `IsDeleted == false`) to every query against a given entity type, without needing to remember to add that filter manually to every single LINQ query throughout the codebase --…

Save .NET mock interview
Advertisement
AModel answer
A global query filter (HasQueryFilter in OnModelCreating) automatically applies a WHERE condition (like `IsDeleted == false`) to every query against a given entity type, without needing to remember to add that filter manually to every single LINQ query throughout the codebase -- implementing soft deletes (marking a row as deleted rather than physically removing it) transparently, while still allowing an explicit .IgnoreQueryFilters() call for the rare cases (like an admin 'view deleted items' feature) that need to see soft-deleted records.
public class Product { public bool IsDeleted { get; set; } }

modelBuilder.Entity<Product>().HasQueryFilter(p => !p.IsDeleted);

// Automatically excludes soft-deleted products from every query:
var products = await context.Products.ToListAsync();  // IsDeleted=true rows never appear

// Explicit override when needed:
var allIncludingDeleted = await context.Products.IgnoreQueryFilters().ToListAsync();
Real-world example
An e-commerce platform implements soft deletes for products (preserving order history references) using a global query filter, ensuring every part of the application automatically excludes deleted products without any developer needing to remember to add that condition manually.
Likely follow-ups
  • How do global query filters interact with navigation property includes?
  • What are the risks of forgetting a soft-delete filter exists when writing raw SQL alongside EF Core?
Related topics