Search code examples
c#linq-to-entitiesexpression-treeslinq-expressionslinqkit

Building a custom predicate to act as a filter using a foreach loop


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.


Solution

  • 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 chain Where query operators to the final query, like this :

    var documents = this.ObjectSet.AsExpandable()
        .Where(mainPredicate)
        .Where(otherPredicate)
        .Where(yetAnotherPredicate)
        .ToList();
    

    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.