如何动态获取构建表达式(c => c.user.code ==' XXX')

时间:2017-06-01 17:56:56

标签: c# entity-framework linq lambda

我构建了一个动态构造表达式的方法,下面是我的代码:

public static Expression<Func<T, bool>> BuildStringEqualLambda(string propertyName, string propertyValue)
{
    ParameterExpression parameterExp = Expression.Parameter(typeof(T), "type");
    Expression propertyExp = Expression.Property(parameterExp, propertyName);
    Expression right = Expression.Constant(propertyValue);
    Expression e1 = Expression.Equal(propertyExp, right);
    return Expression.Lambda<Func<T, bool>>(e1, new ParameterExpression[] { parameterExp });
}

但如果lambda喜欢

c=>c.user.code == 'XXX'

我调用如下方法:

BuildStringEqualLambda("user.code","XXX");

方法报告错误。

所以我的问题是如何动态获取构建表达式(c =&gt; c.user.code ==&#39; XXX&#39;)

1 个答案:

答案 0 :(得分:1)

而不是:

ParameterExpression parameterExp = Expression.Parameter(typeof(T), "type");
Expression propertyExp = Expression.Property(parameterExp, propertyName);

你需要深入了解每个房产:

ParameterExpression parameterExp = Expression.Parameter(typeof(T), "type");
Expression propertyExp = parameterExp;
foreach (var property in propertyName.Split('.')) {
    propertyExp = Expression.PropertyOrField(propertyExp, property);
}