Filtered includes now supported in Entity Framework Core 5.0

Filtered includes is an awesome new feature in Entity Framework Core 5.0 which was released in November 2020.

Without lazy loading (supported but turned off by default in EF Core 2.1+) we need to use the include method to eager load related entities but in Entity Framework Core < 5.0 you couldn’t use filters on the related entities. This meant for example that if you wanted any child posts of a blog you had to load all child posts.. and then filter on the C# side. Obviously depending on the situation this could affect performance. Thankfully the ability to filter the include method is now supported.

In snippet 1 below (click for a larger version in a new window) we can see the LINQ and SQL generated when we include all child posts of each blog. This is all we can do in Entity Framework Core < 5.0 which can result in unneeded data being returned from the DB.

In snippet 2 we can see a sample of the runtime error we’ll get in EF Core < 5.0 when trying to use filtered includes.

And finally in snippet 3 we can see the new EF Core include filter functionality in action where we can see a sample query that gets generated in EF Core 5.0 when using filtered includes. In this case the include is filtered to only return child posts which have ‘Entity Framework’ in their title.

Entity Framework Core Filtered Includes
Note – I’ve just used String.Contains as a simple example of an Entity Framework include filter above but use this with care as it creates a query that is non-sargable (due to the LIKE having a wildcard at the start) meaning it won’t be able to use an index on the title field if there was one.

Leave a Reply

Your email address will not be published. Required fields are marked *