skip to content

In EF Core 10, what can a filtered Include such as Include(p => p.Tracks.Where(...).Take(10)) express, and why can a tracking query still return tracks the filter excluded?

level: seniorimportance: should knowfreq 35%

answer

  1. filter the children, not the parents
  2. Where, OrderBy, ThenBy, Skip, Take
  3. one unique filter per navigation
  4. already-tracked entities join through fix-up
  5. the navigation counts as loaded

basics

~20 s

A filtered Include composes Where, OrderBy(Descending), ThenBy(Descending), Skip and Take on a collection navigation inside Include. In a tracking query, tracks the context already holds are fixed up into the collection even when the filter excludes them.

solid answer

~40 s

`Include(p => p.Tracks.Where(t => !t.IsHidden).OrderByDescending(t => t.PlayCount).Take(10))` loads each playlist with at most its ten most-played visible tracks; it filters the **children**, never the parent playlists. The supported operators are `Where`, `OrderBy`, `OrderByDescending`, `ThenBy`, `ThenByDescending`, `Skip` and `Take`, and a navigation included more than once may carry one unique filter - repeat it identically or put it on one include only. The trap is tracking: the filter shapes the SQL, but navigation fix-up then adds any track the `DbContext` already tracks for that playlist, so the collection can hold rows the filter rejected. EF Core also marks the navigation loaded, so explicit or lazy loading will not fetch the missing ones. When the filtered set must be exact, use `AsNoTracking()`, a fresh context, or a `Select` projection.

code

csharp · 8 lines
csharp
var playlists = await db.Playlists
    .AsNoTracking()
    .Include(p => p.Tracks
        .Where(t => !t.IsHidden)
        .OrderByDescending(t => t.PlayCount)
        .Take(10))
    .ThenInclude(t => t.Artist)
    .ToListAsync();

go deeper

for a junior

Recall that Include can take Where, OrderBy, ThenBy, Skip and Take on a collection, and that it filters the related rows, not the parents.

for a middle

Explain the one-unique-filter rule when a navigation is included twice, and why Skip and Take need an ordering.

for a senior

Diagnose the tracking surprise - fix-up adding already-tracked rows, the navigation marked loaded - and pick AsNoTracking, a fresh context or a projection accordingly.

for a principal

Set a team rule for when collections loaded with filters may be treated as complete, and how read paths and write paths load related data differently.

## Filtering the children, not the parents A **filtered include** is an `Include` whose lambda does more than name a collection navigation: it composes query operators onto it, and EF Core translates them into the SQL that loads the related rows. It answers questions like "each playlist with its ten most-played tracks" in one query. | Query | What is filtered | |---|---| | `db.Playlists.Where(p => p.IsPublic).Include(p => p.Tracks)` | which **playlists** come back; each gets all its tracks | | `db.Playlists.Include(p => p.Tracks.Where(t => !t.IsHidden))` | which **tracks** each playlist gets; every playlist comes back, even one with no visible tracks | | both together | public playlists, each with only its visible tracks | ## Which operators are allowed Inside the `Include` lambda, a collection navigation accepts these operators (plus a no-op `AsQueryable()`): - `Where` - `OrderBy` and `OrderByDescending` - `ThenBy` and `ThenByDescending` - `Skip` and `Take` Anything else - `Select`, `Distinct`, `GroupBy` - makes EF Core throw an `InvalidOperationException` explaining that the expression is invalid inside an `Include` and listing the operators above. Ordering matters with `Skip`/`Take`: without `OrderBy...` the "first ten" are whatever the database returns first. ## One unique filter per navigation Including the same navigation twice to reach two branches is common. EF Core allows a filter on only one of those includes, or the **identical** filter on each: ```csharp // Allowed: filter on one include, plain on the other db.Playlists .Include(p => p.Tracks.Where(t => !t.IsHidden)).ThenInclude(t => t.Artist) .Include(p => p.Tracks).ThenInclude(t => t.Album); // Throws: two different filters on the same navigation db.Playlists .Include(p => p.Tracks.Where(t => !t.IsHidden)).ThenInclude(t => t.Artist) .Include(p => p.Tracks.Where(t => t.PlayCount > 0)).ThenInclude(t => t.Album); ``` The second query fails with "The filters ... have both been configured on the same included navigation. Only one unique filter per navigation is allowed." ## The tracking surprise, step by step 1. Earlier in the request, a tracking query loads playlist 7's tracks for a duplicate check; the `DbContext` now tracks all 40 of them. 2. The page then runs `Include(p => p.Tracks.Where(t => t.PlayCount > 1000))` for playlist 7 as a tracking query. 3. The SQL correctly returns only the 6 popular tracks. 4. Because the query tracks, EF Core performs **navigation fix-up**: every tracked `Track` whose foreign key points at playlist 7 is wired into `playlist.Tracks`. 5. The page shows 40 tracks, not 6. The EF Core docs state this explicitly: with tracking queries, all relevant entities already in the change tracker appear in the results of a filtered include even when they do not meet the filter. ## The navigation counts as loaded In a tracking query, EF Core treats a navigation loaded through a filtered include as **loaded**. So `db.Entry(playlist).Collection(p => p.Tracks).LoadAsync()` is a no-op afterwards, and lazy loading will not fire either - even though most tracks were never fetched. Code that later assumes `playlist.Tracks` is complete (to compute a total duration, say) silently works on a subset. ## Choosing the remedy - **`AsNoTracking()`** - no change tracker, no fix-up: the collection holds exactly what the filter returned. Right for read-only pages. - **A fresh, short-lived `DbContext`** - nothing is tracked beforehand. In ASP.NET Core the scoped context usually already gives one per request; the problem appears when one request runs several queries. - **A `Select` projection** - `p.Tracks.Where(...).OrderByDescending(...).Take(10).Select(t => new TrackRow(...))` returns DTOs, which are never tracked or fixed up. - **Keep it tracked** only when you intend to modify the loaded tracks and call `SaveChanges`, and then do not treat the collection as the playlist's complete set. ## Paging children per parent A filtered include is also the EF Core way to page **each** parent's children - "the latest five tracks of every playlist" - inside one query, which a root-level `Take` cannot express because it limits parents, not children. Always pair `Skip`/`Take` with an explicit ordering, and remember that the result is still a partial collection: a page that shows "5 of 212 tracks" needs the total from a separate aggregate, such as `p.Tracks.Count()` in a projection. The senior point is that a filtered include is a **load shape**, not a **view**: with tracking on, the collection reflects everything the context knows about that playlist.

  • Does a filtered Include drop playlists that have no matching tracks?
    No. The filter applies to the related rows only; every playlist the root query selects comes back, some with an empty `Tracks` collection. To return only playlists that have matching tracks, filter the root as well, for example `.Where(p => p.Tracks.Any(t => !t.IsHidden))`.
  • How do you combine a filtered collection with two ThenInclude branches below it?
    Put the filter on one `Include` of the collection and leave the other plain, or repeat the identical filter on both. Two different filters on the same navigation throw an `InvalidOperationException` saying only one unique filter per navigation is allowed.

  • A filtered Include also removes playlists that have no matching tracks.
  • Any LINQ operator, including Select and Distinct, can be used inside Include.
  • A tracking query with a filtered Include returns exactly the rows the filter matched.
  • Two Includes of the same navigation may carry different filters.
  • After a filtered Include, LoadAsync on that collection fetches the excluded tracks.