I need to filter a list of documents by passing them to a custom filter that I'm struggling to build dynamically using a foreach
loop :
var mainPredicate = PredicateBuilder.True<Document>();
// mainPredicate is combined to other filters successfully here ...
var innerPredicate = PredicateBuilder.False<Document>();
foreach (var period in periods)
{
var p = period;
Expression<Func<Document, bool>> inPeriod =
d => d.Date >= p.DateFrom && d.Date <= p.DateTo;
innerPredicate = innerPredicate.Or(d => inPeriod.Invoke(d));
}
mainPredicate = mainPredicate.And(innerPredicate);
This last line :
documents = this.ObjectSet.AsExpandable().Where(mainPredicate).ToList();
Throws this exception :
The parameter 'd' was not bound in the specified LINQ to Entities query expression.
Anyone knows why I'm getting this exception ? I don't understand where the 'd' parameter I am passing to the InPeriod method gets lost. I don't know what is missing for this to work. My code is the same as many other examples that work perfectly. Any additionnal theoric theoric information about invoking expressions and how it works behind the scenes are welcome.
Finally, I have found a way to avoid combining multiple predicates to the main expression tree.
Given that each predicate represents a different filter and I want the final, combined filter to be a series of must-be-respected conditions, we can say that each of the predicates has to return true for the final predicate to return true.
For that to work, the predicates has to be combined with
AND
. So, the resulting SQL query must look like this :predicate1 AND predicate2 AND predicate3
...A better way to combine these predicates with
AND
is to chainWhere
query operators to the final query, like this :The resulting SQL query will combine each of these predicates with
AND
. That is just what I wanted to do.It is easier than hacking out an expression tree by myself.
I use these extension methods:
I don't understand why you do this:
When you could just avoid the
Invoke
completely, like this:This should work perfectly fine.
BTW, I have a feeling there's a bug with LINQKit here (unless there's some documentation that suggests that it doesn't support this scenario).
When I tried this similar code:
...LINQKit generated the following composite expression:
... which indeed has the unbound parameter d (NodeType = Parameter, Name = 'd').
Dodging the
Invoke
withfirst.Or(second).Expand()
generates the perfectly sensible: