C# PredicateBuilder Entities: The parameter 'f' was not bound in the specified LINQ to Entities query expression

前端 未结 2 733
暗喜
暗喜 2020-12-04 12:08

I needed to build a dynamic filter and I wanted to keep using entities. Because of this reason I wanted to use the PredicateBuilder from albahari.

I created the foll

2条回答
  •  不知归路
    2020-12-04 12:37

    I ran across the same error, the issue seemed to be when I had predicates made with PredicateBuilder that were in turn made up of other predicates made with PredicateBuilder

    e.g. (A OR B) AND (X OR Y) where one builder creates A OR B, one creates X OR Y and a third ANDs them together.

    With just one level of predicates AsExpandable worked fine, when more than one level was introduced I got the same error.

    I wasn't able to find any help but through some trial and error I was able to get things to work. Every time I called a predicate I followed it with the Expand extension method.

    Here is a bit of the code, cut down for simplicity:

    public static IQueryable AddOptionFilter(
        this IQueryable query, 
        IEnumerable> options)
    {
        var predicate = options.Aggregate(
            PredicateBuilder.False(),
            (accumulator, optionIds) => accumulator.Or(ConstructOptionMatchPredicate(optionIds).Expand()));
            query = query.Where(predicate.Expand());            
        return query;
    }
    

    Query is an IQueryable which has already had AsExpandable called, ConstructOptionNotMatchPredicate returns an Expression.

    Once we got past the error we were certainly able to build up complicated filters at runtime against the entity framework.

    Edit:

    Since people are still commenting on and up voting this I assume it is still useful so I am sharing another fix. Basically I have stopped using LinqKit and it's predicate builder in favour of this Universal Predicate Builder that has the same API but doesn't need Expand calls, well worth checking out.

提交回复
热议问题