Filtering on Include in EF Core

entity-framework-core

Question

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)
        .ToList();
}

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

1
41
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.

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

or

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)

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

1
4/10/2020 7:50:15 PM

Popular Answer

Not doable.

There is an on-going discussion about this topic: https://github.com/aspnet/EntityFramework/issues/1833

I'd suggest to look around for any of the 3rd party libraries listed there, ex.: https://github.com/jbogard/EntityFramework.Filters



Related Questions





Related

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