For years (quite literally 3 years) I’ve been waiting for filtering to be available on includes within Entity Framework, or more specifically, EF Core. Finally, the next preview should have this included. From the pull request, the additional operations to be specified inside Include/ThenInclude are:

  • Where
  • OrderBy(Descending)/ThenBy(Descending)
  • Skip
  • Take

The original request has been updated to show a few of the supported examples and restrictions. From the original request, note that only one filter allowed per navigation, so for cases where the same navigation needs to be included multiple times (e.g. multiple ThenInclude on the same navigation) apply the filter only once, or apply exactly the same filter for that navigation.

Example:

1
2
3
customers 
    .Include(c => c.Orders.Where(o => o.Name != "Foo")).ThenInclude(o => o.OrderDetails) 
    .Include(c => c.Orders).ThenInclude(o => o.Customer)

or

1
2
3
customers
    .Include(c => c.Orders.Where(o => o.Name != "Foo")).ThenInclude(o => o.OrderDetails)
    .Include(c => c.Orders.Where(o => o.Name != "Foo")).ThenInclude(o => o.Customer)

Special thanks to Maurycy Markowski for updating us all and Gert Arnold for updating my original Stack Overflow request.