Question

I want to build lambda expression :

Expression<Func<MyObject, bool>> predicate = PredicateBuilder.False<MyObject>();
var param = Expression.Parameter(typeof(MyObject), "f");

if (myOperator == OperateurEnum.EG)
{
    var body = Expression.Equal(
        Expression.PropertyOrField(param, myProperty),
        Expression.Constant(myFilterValue)
    );

    var lambda = Expression.Lambda<Func<MyObject, bool>>(body, param);
    predicate = predicate.Or(lambda);
}
else if (myOperator == OperateurEnum.CT)
{
    var body = Expression.Call(
        Expression.PropertyOrField(param, myProperty),
        "StartsWith",
        null,
        Expression.Constant(myFilterValue)
    );

    var lambda = Expression.Lambda<Func<MyObject, bool>>(body, param);
    predicate = predicate.Or(lambda);
}
else if ()
{
    ...
}

var myEx = Expression.Lambda<Func<MyObject, bool>>(predicate.Body, param);
Func<MyObject, bool> lambdaDelegate = myEx.Compile();

I use PredicateBuilder, but I got this error :

variable 'f' of type 'ProactisMvc.Web.ProactisWsServiceReference.Offre' referenced from scope '', but it is not defined

What's wrong ? Is there another solution ?

Était-ce utile?

La solution

This last bit is wrong:

var myEx = Expression.Lambda<Func<MyObject, bool>>(predicate.Body, param);
Func<MyObject, bool> lambdaDelegate = myEx.Compile();

You are creating a new expression using predicate's body but with some other parameter. This will mean that that the parameter-expressions used inside the expression- body will not be the ones accepted by the top-level expression!

Perhaps you are confused by PredicateBuilder's magic, but all .Or is doing is combining the two predicates using an || expression, invoking the second predicate using the first predicate's parameter.

I think you just want:

var myDelegate = predicate.Compile();
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top