Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I use a Predicate<T> in an EF Where() clause?

Tags:

People also ask

How to use where() in c#?

The where clause is used in a query expression to specify which elements from the data source will be returned in the query expression. It applies a Boolean condition (predicate) to each source element (referenced by the range variable) and returns those for which the specified condition is true.

What is predicate in Linq C#?

A predicate, or more precisely a predicate functor, is a Boolean-valued function. It is often a unary function, checking one argument against a condition and returning the result. Disregarding functions depending on side effects, there are two nullary functions (without arguments). public static class Predicate.


I'm trying to use predicates in my EF filtering code.

This works:

IQueryable<Customer> filtered = customers.Where(x => x.HasMoney && x.WantsProduct);

But this:

Predicate<T> hasMoney = x => x.HasMoney;
Predicate<T> wantsProduct = x => x.WantsProduct;
IQueryable<Customer> filtered = customers.Where(x => hasMoney(x) && wantsProduct(x));

fails at runtime:

The LINQ expression node type 'Invoke' is not supported in LINQ to Entities.

I can't use the first option, as this is a simple example, and in reality, I'm trying to combine a bunch of predicates together (with and, not, or, etc.) to achieve what I want.

How can I get the EF Linq provider to "understand" my predicate(s)?

I get the same result if I use a Func<T, bool>. It works with an Expression<Func<T>>, but I can't combine expressions together for complex filtering. I'd prefer to avoid external libraries if possible.

UPDATE:
If this cannot be done, what options do I have? Perhaps expressions be combined / or'ed / and'ed somehow to achieve the same effect?