skip to content

In EF Core 10, how do you hide soft-deleted forum posts from every query with HasQueryFilter, and how does a moderator page still see them?

level: juniorimportance: must knowfreq 55%

answer

  1. configured once in OnModelCreating
  2. an extra Where on every query of the type
  3. applies to navigations and Include too
  4. IgnoreQueryFilters() per query
  5. deleting still needs IsDeleted = true

basics

~10 s

Configure modelBuilder.Entity<Post>().HasQueryFilter(p => !p.IsDeleted) in OnModelCreating; EF adds that condition to every query of Post, including Include and navigations. A moderator query calls IgnoreQueryFilters() to switch filters off for that one query.

solid answer

~40 s

A global query filter is a predicate attached to an entity type in the model: `modelBuilder.Entity<Post>().HasQueryFilter(p => !p.IsDeleted)`. EF Core then adds it, like an extra `Where`, to every LINQ query that reaches `Post` — `db.Posts`, a `Post` loaded through `Include`, a navigation used in a projection, `FromSql` on the `DbSet`, even `ExecuteUpdate`. A moderator page that must list deleted posts adds `.IgnoreQueryFilters()` to its query, which disables the filters for every entity type in that query. The filter only hides rows: deleting a post still means setting `IsDeleted = true` and saving, usually by converting `Remove` into an update in a `SaveChanges` override or interceptor. An index that covers the `IsDeleted` condition keeps the extra predicate cheap.

code

csharp · 7 lines
csharp
app.MapGet("/mod/threads/{id:int}/deleted", async (int id, ForumDbContext db, CancellationToken ct) =>
    await db.Posts
        .IgnoreQueryFilters()
        .Where(p => p.ThreadId == id && p.IsDeleted)
        .OrderByDescending(p => p.DeletedAt)
        .ToListAsync(ct))
    .RequireAuthorization("Moderator");

go deeper

for a junior

Recall HasQueryFilter in OnModelCreating for soft delete and IgnoreQueryFilters() for the one query that needs deleted rows.

for a middle

Explain that the filter belongs to the entity type, so it also applies to Include, navigations and FromSql, and that IgnoreQueryFilters is query-wide.

for a senior

Design the write side, indexes and unique constraints around soft delete, and make every bypass explicit and authorized.

for a principal

Decide whether soft delete is worth its cost per aggregate, and how retention and hard purges fit legal and storage needs.

## What a global query filter is A **global query filter** is a boolean predicate attached to an entity type in the EF Core model. Whenever a query touches that entity type, EF adds the predicate as if you had written an extra `Where`. You configure it once, in `OnModelCreating` or an `IEntityTypeConfiguration<T>`, with `HasQueryFilter`. On a multi-tenant discussion forum, deleted posts stay in the table so moderators can restore them: ```csharp public class Post { public int Id { get; set; } public int ThreadId { get; set; } public string Body { get; set; } = ""; public bool IsDeleted { get; set; } public DateTime? DeletedAt { get; set; } } protected override void OnModelCreating(ModelBuilder modelBuilder) { modelBuilder.Entity<Post>().HasQueryFilter(p => !p.IsDeleted); } ``` Now `await db.Posts.Where(p => p.ThreadId == threadId).ToListAsync()` sends SQL whose `WHERE` clause contains both the thread condition and `NOT (p."IsDeleted")`. ## Where the filter applies The filter belongs to the entity type, not to the `DbSet`, so it is applied wherever EF builds a query over `Post`: - queries rooted at `db.Posts` or `db.Set<Post>()`; - posts loaded through `Include(t => t.Posts)` on a thread; - navigations used inside projections, such as `t.Posts.Count()`; - queries that start with `FromSql` on `db.Posts`; - `ExecuteUpdate` and `ExecuteDelete` over `db.Posts`, which only touch rows the filter lets through. It does **not** reach SQL that EF does not build from the model: `Database.SqlQuery<T>`, `Database.ExecuteSql`, or plain ADO.NET. ## Turning it off for one query A moderation screen calls `IgnoreQueryFilters()`: ```csharp var deleted = await db.Posts .IgnoreQueryFilters() .Where(p => p.IsDeleted && p.DeletedAt > since) .ToListAsync(ct); ``` Two details matter: 1. `IgnoreQueryFilters()` is **query-wide**: it disables the filters of every entity type the query touches, including included and navigated ones, not only `Post`. 2. It is opt-out per query. There is no setting on the context that disables filters for all queries, which is deliberate: bypassing must be visible at the call site. ## Writing the deletion The filter only hides rows. Something must still set the flag: | Approach | How it works | |---|---| | Explicit update | `post.IsDeleted = true; post.DeletedAt = now; await db.SaveChangesAsync();` | | Convert removals | override `SaveChangesAsync` or use an interceptor to turn `Deleted` entries of soft-deletable types into `Modified` with the flag set | | Bulk | `db.Posts.Where(...).ExecuteUpdateAsync(s => s.SetProperty(p => p.IsDeleted, true))` | Converting removals lets the rest of the code call `db.Posts.Remove(post)` as usual. ## How the filter appears in SQL Because the filter is added during translation, it shows up in the generated SQL like any other predicate, and `ToQueryString()` displays it. For the thread query above the `WHERE` clause holds both conditions, combined with `AND`. Two consequences follow: - The database can use an index that covers both conditions, so the filter does not have to cost a scan. - A filter that EF cannot translate makes **every** query on the type fail, so keep filters to simple property comparisons. ## Practical notes - The filter costs a predicate on every query. A partial index on non-deleted rows, or a composite index that includes `IsDeleted`, keeps it cheap. - Unique constraints must account for deleted rows: a deleted post's slug may block a new one unless the index excludes deleted rows. - A filter is part of the model, so it is the same for every query; behaviour that varies per request needs a context-level value, covered by tenant filters.

  • Does IgnoreQueryFilters() on db.Threads.Include(t => t.Posts) also show deleted posts?
    Yes. `IgnoreQueryFilters()` applies to the whole query, so the filters of every entity type in it are switched off, including the `Post` filter on the included collection. To keep a different filter active, EF Core 10's named filters let you ignore only selected filters.
  • Why doesn't HasQueryFilter by itself make db.Posts.Remove(post) a soft delete?
    The filter only shapes queries; it says nothing about writes. `Remove` marks the entry `Deleted`, and `SaveChanges` sends a `DELETE`. To soft-delete, set `IsDeleted` explicitly or intercept deleted entries before saving and switch them to `Modified` with the flag set.

A soft-delete filter is like a library that keeps withdrawn books on a staff-only shelf: every catalogue search skips that shelf automatically, and only a librarian who explicitly asks for staff access sees those books again.

  • HasQueryFilter physically deletes rows marked IsDeleted.
  • The filter applies only to queries that start from db.Posts.
  • IgnoreQueryFilters() removes the filter for the rest of the context's life.
  • Database.SqlQuery<T> results are filtered by HasQueryFilter too.
  • Calling Remove on a filtered entity soft-deletes it automatically.

Assumes EF Core 10; HasQueryFilter and the parameterless IgnoreQueryFilters() behave as in EF Core 8 and 9, while ignoring individual named filters is new in EF Core 10.