الانتقال إلى المحتوى
.NETEF Core· 8 دقائق للقراءة

Soft Delete Is More Than an IsDeleted Flag: Global Query Filters in EF Core

A query filter only hides rows from LINQ reads. Cascades, unique indexes, required navigations, bulk deletes and IgnoreQueryFilters all still need a decision.

ReadIn

مقال كل يوم يفرق معاك

22 نوفمبر 2026
  • كاتب موثّق
  • EF Core 10
محتويات المقال

A customer closes her account, and the app soft-deletes it. A month later she signs up again with the same email and gets a 500: Cannot insert duplicate key row in object 'dbo.Customers' with unique index 'IX_Customers_Email'. Meanwhile her orders still count in the sales report but vanish from the order page that shows the customer's name. And the new admin "Trash" page, built with IgnoreQueryFilters(), lists deleted customers from every tenant, not just the admin's own.

The common misconception

The belief: soft delete is an IsDeleted column plus a global query filter, and everything else keeps working as before. Deleted rows disappear from queries, Include and navigations respect the filter, and nothing else in the app has to know.

That's how EF Core's own documentation introduces query filters: its first example is soft deletion with HasQueryFilter(b => !b.IsDeleted), and it really does hide those rows from every LINQ query on that type, including loads through navigations. The half-truth is the word "everything". The filter changes reads. Deleting, constraints and relationships work exactly as they did before, and they still think the row exists.

What actually happens

Deletes stop cascading the way you expect

The docs suggest overriding SaveChanges to turn Deleted entries into updates that set IsDeleted. Write that for Customer only, and EF's still runs for the orders it tracks: in a test with EF Core 10 on SQL Server LocalDB, one save sent an UPDATE for the customer and a DELETE for each loaded order. Orders that weren't loaded were left alone, because the database cascade only fires on a real DELETE, and none was sent.

The bulk path skips your logic entirely. ExecuteDeleteAsync doesn't go through SaveChanges, so in the test it physically deleted the customer, and ON DELETE CASCADE deleted her orders with it. The query filter was still applied to its WHERE clause, so it only deleted rows the filter could see. The cascade-delete docs say it plainly: don't configure cascade delete in the database when soft-deleting entities.

Unique indexes still see deleted rows

An index knows nothing about your query filter. The soft-deleted row still holds mona@x.com, so the unique index rejected the new signup, exactly as in the hook. EF Core can create a with HasFilter, on databases that support it, so only live rows compete for the value. With HasFilter("[IsDeleted] = 0"), the same signup succeeded.

Required navigations hide live rows

The filter docs carry a caution about this. When the navigation to a filtered entity is required, EF may use an INNER JOIN, and rows whose parent is filtered out disappear. In the test, Orders.CountAsync() returned 3 while Orders.Include(o => o.Customer) returned 1. The docs offer two fixes: make the navigation optional, or give the dependent a matching filter, so both queries agree.

IgnoreQueryFilters() turns off every filter

Before EF Core 10, an entity had one filter, so soft delete and tenant isolation were combined with &&. IgnoreQueryFilters() then removes both, which is how the trash page returned another tenant's customer in the test. EF Core 10 adds named query filters, and IgnoreQueryFilters(["SoftDelete"]) removes just that one: the same page then listed only the current tenant's rows, deleted ones included.

The fix: make deleting a decision

C# ShopDb.cs
using Microsoft.EntityFrameworkCore;public sealed class ShopDb(DbContextOptions<ShopDb> options, ITenant tenant)    : DbContext(options){    public DbSet<Customer> Customers => Set<Customer>();    public DbSet<Order> Orders => Set<Order>();    protected override void OnModelCreating(ModelBuilder b)    {        // One unnamed filter: IgnoreQueryFilters() drops the tenant check too        b.Entity<Customer>()            .HasQueryFilter(c => !c.IsDeleted && c.TenantId == tenant.Id);        // Deleted customers keep their email forever        b.Entity<Customer>().HasIndex(c => c.Email).IsUnique();        // Orders: no filter, and ON DELETE CASCADE in the database    }}

ClientCascade keeps the cascade for tracked entities but creates no database cascade, so in the test a stray ExecuteDeleteAsync on a customer with orders failed with a foreign key error instead of silently deleting them. Then one interceptor turns every delete EF tracks into an update:

C# SoftDeleteInterceptor.cs
using Microsoft.EntityFrameworkCore;using Microsoft.EntityFrameworkCore.Diagnostics;// Register with options.AddInterceptors(new SoftDeleteInterceptor())public sealed class SoftDeleteInterceptor : SaveChangesInterceptor{    public override ValueTask<InterceptionResult<int>> SavingChangesAsync(        DbContextEventData data, InterceptionResult<int> result,        CancellationToken ct = default)    {        // Every soft-deletable entry, including orders EF cascaded to Deleted        foreach (var e in data.Context!.ChangeTracker.Entries<ISoftDelete>())        {            if (e.State != EntityState.Deleted) continue;            e.State = EntityState.Modified;            e.Entity.IsDeleted = true;            e.Entity.DeletedAt = DateTime.UtcNow;        }        return base.SavingChangesAsync(data, result, ct);    }}

With both in place, removing a customer with loaded orders sent three UPDATE statements and no DELETE. The interceptor docs note that every interception point has a sync and an async method, so override SavingChanges too if anything calls SaveChanges.

ConcernIsDeleted plus one filterSoft delete designed on purpose
LINQ readsDeleted rows hiddenDeleted rows hidden
Loaded dependentsHard-deleted by EF's cascadeSoft-deleted by the interceptor
Unique valuesHeld by deleted rowsReleased by a filtered index
Include on a required navigationDrops rows whose parent is deletedSame answer as a plain count
Admin view of deleted rowsAlso shows other tenantsIgnoreQueryFilters(["SoftDelete"]) keeps the tenant filter

How to apply it in your project

  1. List every delete pathSearch for Remove, ExecuteDelete, raw SQL deletes and database cascades on soft-deleted types, and make each one an update or a deliberate hard delete.
  2. Fix the schemaFilter unique indexes on IsDeleted, and switch relationships of soft-deleted types to ClientCascade, so EF still cascades to tracked entities and the database never cascades a real delete.
  3. Name the filtersOn EF Core 10, split soft delete and tenancy into named filters, and replace bare IgnoreQueryFilters() calls with the names you mean.
  4. Test the edgesWrite integration tests for re-creating a deleted unique value, Include across a deleted parent, and restoring a row.

Key takeaways

  • A global query filter only adds a Where to LINQ queries; deletes, constraints and joins don't know about it.
  • EF still cascades real deletes to tracked dependents, and ExecuteDelete bypasses SaveChanges logic entirely.
  • Unique indexes need HasFilter, or deleted rows keep their values.
  • Required navigations can drop live rows whose parent is filtered out; give dependents a matching filter.
  • In EF Core 10, name your filters so IgnoreQueryFilters never switches off tenant isolation by accident.

📚 المصادر

  1. Global Query Filters — EF Core, Microsoft Learn
  2. What's New in EF Core 10: named query filters — Microsoft Learn
  3. Cascade Delete — EF Core, Microsoft Learn
  4. Indexes: index filter — EF Core, Microsoft Learn
  5. Interceptors: SaveChanges interception — EF Core, Microsoft Learn

التعليقات (0)