开发者

What's wrong with this linq expression creation (using contains)

开发者 https://www.devze.com 2023-03-25 00:46 出处:网络
I am trying to dynamically create a linq expression with the contains operator. After reading several posts related to this topic, I have come up with the following code that allows me to perform a \

I am trying to dynamically create a linq expression with the contains operator.

After reading several posts related to this topic, I have come up with the following code that allows me to perform a "contains" like evaluation:

internal static Expression<Func<TEntity, bool>> StringContains<TEntity>(string propertyName, string subString)
{
    MethodInfo contains = typeof(JsonLinqParser_Paser).GetMethod("Like");
    var param = Expression.Parameter(typeof(TEntity));
    var body = Expression.Call(contains, Expression.Property(param, propertyName), Expression.Constant(subString, typeof(string)));

    var lambda = Expression.Lambda<Func<TEntity, bool>>(body, param);

    return lambda;
}
public static bool Like(string a, string b)
{
    return a.Contains(b);
}

And this is called like so:

var expression = Expression.Lambda<Func<TEntity, bool>>(StringContains<TEntity>("FIPSCO_STR", _开发者_如何学CmyStringValue), param);

However, at runtime, I get an error as follows:

Expression of type 'System.Func`2[DAL.BestAvailableFIP,System.Boolean]' cannot be used for return type 'System.Boolean'

where "DAL.BestAvailableFIP" is the "TEntity" type.

I'm sure this is all related to my lack of knowledge regarding lambda expressions. Can anyone tell me what I'm doing wrong?


StringContains already returns a LambdaExpression.

You shouldn't put it in another lambda expression.
If you want to create another lambda expression that contains it, you should use its Body.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号