Filtering on Include in EF Core



I'm trying to filter on the initial query. I have nested include leafs off a model. I'm trying to filter based on a property on one of the includes. For example:

using (var context = new BloggingContext())
    var blogs = context.Blogs
        .Include(blog => blog.Posts)
            .ThenInclude(post => post.Author)

How can I also say .Where(w => == "me")?

7/19/2019 1:38:11 AM

Accepted Answer

Finally, this feature has been implemented. It'll be available in the next preview.

Supported operations:

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

Some usage examples (from the original feature request):

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.

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


    .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)

Another important note:

Collections included using new filter operations are considered to be loaded.

That means that if lazy loading is enabled, addressing customers.Orders from the last example won't trigger a reload of the entire Orders collection.

On the other hand, if other Orders are loaded into the same context, more of them may get added to a customers.Orders collection because of relationship fixup. (I didn't verify that yet, but it seems inevitable because of how EF's change tracker works).

4/10/2020 7:50:15 PM

Popular Answer

Not doable.

There is an on-going discussion about this topic:

I'd suggest to look around for any of the 3rd party libraries listed there, ex.:

Related Questions


Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow