EF Core 5 - Extension method on filter include

Viewed 883

I'm trying the new, awesome and finally implemented "Filtered Include" on EF Core 5 (preview 3).

This code is perfectly working

var categoriesWithActiveProducts = await _context.Categories.Include(x => x.Products.Where(y => y.IsActive)).ToListAsync();

Well, now I'd like to use an extension method to make the code more intuitive, so

var categoriesWithActiveProducts = await _context.Categories.Include(x => x.Products.ActiveQueryFilter()).ToListAsync();

public static IEnumerable<Product> ActiveQueryFilter(this ICollection<Product> source)
{
    return source.Where(x => x.IsActive).AsEnumerable();
}

But I get the error below

System.InvalidOperationException: The expression 'x.Products.ActiveQueryFilter()' is invalid inside Include operation. The expression should represent a property access: 't => t.MyProperty'. To target navigations declared on derived types use cast, e.g. 't => ((Derived)t).MyProperty' or 'as' operator, e.g. 't => (t as Derived).MyProperty'. Collection navigation access can be filtered by composing Where, OrderBy(Descending), ThenBy(Descending), Skip or Take operations. For more information on including related data, see http://go.microsoft.com/fwlink/?LinkID=746393.

How can I solve it?

1 Answers

I do not recommend to use a static method in an EF query. The documentation explains why

Basically they can cause memory leaks and unexpected behaviour

Related