简体   繁体   中英

Convert from Expression<Func<TModel, string>> to Expression<Func<TModel, bool>>

What I would like is that if I have Expression like 'e => e.Name' and a value 'Brad', I want to compose/modify it to 'e => e.Name.Contain("Brad")' or 'e => e.Name == "Brad"'.

I was writing like below:

    public Expression<Func<TModel, bool>> ToBool(Expression<Func<TModel, object>> source, string value)
    {
        ParameterExpression paramExpression = Expression.Parameter(typeof(TModel), "u");
        ConstantExpression valueExpression = Expression.Constant(value, typeof(string));
        BinaryExpression equalValue = Expression.MakeBinary(ExpressionType.Equal, source.Body, valueExpression);
        Expression<Func<TModel, bool>> lambdaResult = Expression.Lambda<Func<TModel, bool>>(equalValue, new ParameterExpression[] { paramExpression });
        return lambdaResult;
    }

I keep getting an error "The parameter u was not bound in the specified LINQ to Entities query expression" when the query is triggered.

Would you please point out what I'm doing wrong here?

Thanks a lot for your help

source.Body references the ParameterExpression from the original lambda, which you never declare in your new lambda.
Your new u parameter is never used.

You should reuse source.Parameters[0] instead of creating a new parameter.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM