skip to content

An EF Core 10 forum page lists comments with Include(c => c.Post) and some comments vanish when their post is soft-deleted; why, and how do you fix it?

level: seniorimportance: should knowfreq 30%

answer

  1. required navigation means INNER JOIN
  2. filtered principal removes the dependent row
  3. PossibleIncorrectRequiredNavigationWithQueryFilterInteractionWarning
  4. matching filter on the dependent
  5. or make the navigation optional

basics

~20 s

Comment.Post is required, so EF joins posts with an INNER JOIN, and the Post filter removes deleted posts from that join along with their comments. Add a matching Comment filter, or make the navigation optional so EF uses LEFT JOIN.

solid answer

~40 s

A **required** navigation tells EF the principal always exists, so `Include(c => c.Post)` is translated with an `INNER JOIN`. The `Post` query filter is applied inside that join, so a soft-deleted post disappears from the joined set and every comment pointing at it vanishes too: `db.Comments.ToListAsync()` and `db.Comments.Include(c => c.Post).ToListAsync()` return different counts. EF warns at model validation with `CoreEventId.PossibleIncorrectRequiredNavigationWithQueryFilterInteractionWarning` when a principal with a filter is the required end of a relationship whose dependent has no matching filter. The fixes: give `Comment` a **matching filter**, for example `c => !c.Post.IsDeleted` or its own `IsDeleted`, so both queries agree; or configure the navigation as **optional**, which makes EF use a `LEFT JOIN` and return those comments with `Post` null. Which is right depends on whether a deleted post's comments should still be visible.

code

csharp · 5 lines
csharp
modelBuilder.Entity<Post>()
    .HasQueryFilter(p => !p.IsDeleted);

modelBuilder.Entity<Comment>()
    .HasQueryFilter(c => !c.Post.IsDeleted);

go deeper

for a junior

Remember that a filter on a principal can hide dependents when they are loaded through a required navigation.

for a middle

Explain why required navigations become INNER JOINs and how the filtered principal removes rows from the join.

for a senior

Read the model-validation warning, pick a matching filter or an optional navigation based on the product rule, and keep both queries consistent.

for a principal

Set modelling conventions so every filtered aggregate carries consistent filters on its dependents across the model.

## The symptom On the forum, each `Comment` belongs to exactly one `Post`, configured as a **required** relationship (a non-nullable foreign key `PostId`). `Post` has a soft-delete filter. A moderation report shows two different numbers: ```csharp var all = await db.Comments.CountAsync(ct); // 6 var withPost = await db.Comments.Include(c => c.Post).ToListAsync(ct); // 3 comments ``` The second query returns fewer comments than the first, although `Include` should only add data. ## Why it happens A required navigation promises EF that the related principal **always exists**. EF uses that promise to choose an `INNER JOIN` when it loads the principal. The query filter on `Post` is applied to the joined set, so the SQL is shaped like: ```sql SELECT c."Id", c."Body", c."PostId", p0."Id", p0."Body", p0."IsDeleted" FROM "Comments" AS c INNER JOIN ( SELECT p."Id", p."Body", p."IsDeleted" FROM "Posts" AS p WHERE NOT (p."IsDeleted") ) AS p0 ON c."PostId" = p0."Id" ``` Comments whose post is soft-deleted find no row to join and drop out. The same thing happens with other constructs that make EF join through the required navigation, such as projecting `c.Post.Title`. ## EF tells you at startup When it validates the model, EF logs `CoreEventId.PossibleIncorrectRequiredNavigationWithQueryFilterInteractionWarning` if an entity type with a query filter is the **required** end of a relationship and the dependent has **no matching filter**. The message suggests both fixes: configure the navigation as optional, or define matching filters. Treat that warning as a design question, not noise. ## Fix 1: a matching filter on the dependent Decide that comments of a deleted post are hidden too, and say so in the model: ```csharp modelBuilder.Entity<Post>().HasQueryFilter(p => !p.IsDeleted); modelBuilder.Entity<Comment>().HasQueryFilter(c => !c.Post.IsDeleted); ``` Now both queries return the same three comments. A filter may use navigations, as here; EF translates it into a join or subquery. An alternative is a separate `Comment.IsDeleted` flag set when its post is deleted. ## Fix 2: an optional navigation Decide that comments stay visible even after their post is deleted: ```csharp modelBuilder.Entity<Comment>() .HasOne(c => c.Post).WithMany(p => p.Comments) .HasForeignKey(c => c.PostId) .IsRequired(false); ``` EF now uses a `LEFT JOIN`, returns all six comments, and leaves `Post` **null** for the three whose post is filtered out. Code that reads `comment.Post.Title` must handle null. ## Choosing | Question | Matching filter | Optional navigation | |---|---|---| | Should comments of deleted posts be visible? | no | yes | | Does `comment.Post` ever come back null? | no | yes, when filtered | | Do the two queries agree? | yes | yes | | Model change | filter only | relationship configuration | Questions to settle before choosing: 1. What should a reader see for a comment whose post was removed: nothing, or the comment with a "post removed" placeholder? 2. Does any code path assume `comment.Post` is never null? An optional navigation breaks that assumption. 3. Are there other dependents of `Post`, such as reactions or attachments, that need the same decision? 4. Will moderators, who bypass the soft-delete filter, still see consistent data in both shapes? Making a relationship optional just to silence the warning changes the model's meaning, so pick the option that matches the product rule. In the tenant case the choice is easier: every tenant-owned type should carry the tenant filter, which keeps dependents and principals consistent.

  • After making Comment.Post optional, what does Include(c => c.Post) return for a comment whose post is soft-deleted?
    The comment itself, with `Post` set to null. EF switches to a `LEFT JOIN`, and the filtered-out post produces no matching row, so the navigation is not populated. Code reading `comment.Post` must handle null, which is the price of keeping those comments visible.
  • When does EF log PossibleIncorrectRequiredNavigationWithQueryFilterInteractionWarning?
    During model validation, when an entity type with a global query filter is the required end of a relationship and the dependent entity type has no matching filter. It flags exactly the shape that makes an `INNER JOIN` silently drop dependents.

  • Include only adds data, so it can never reduce the row count.
  • EF always uses LEFT JOIN for Include.
  • Query filters cannot reference navigation properties.
  • Making every navigation optional is the standard fix.