0

我有这个代码:

var listExpression = new List<Expression>();
var parameter = Expression.Parameter(typeof(T));

var memberExpression = Expression.PropertyOrField(parameter, MyProperty);
    listExpression.Add(
    Expression.Call(
        ((MemberExpression)memberExpression), "Contains", null,
        Expression.Constant((string)MyValue))
    );

Expression body = Expression.Constant(true);
foreach (var expression in listExpression)
    body = Expression.And(body, expression);

return Expression.Lambda<Func<T, bool>>(body, parameter);

结果是:

"True & $var1.AGE >= 5"

当我将此谓词与实体框架一起使用但不适用于 NHiernate 时,我没有任何问题。我认为问题是“真”。没有这个 "True" 是否可以创建这个谓词?

4

1 回答 1

1

代替

Expression body = Expression.Constant(true);
foreach (var expression in listExpression)
    body = Expression.And(body, expression);

经过

var body = listExpression.First();//check first if listExpression.Any() would be better
listExpression.Skip(1).Aggregate(body, Expression.And);
于 2012-09-04T18:43:37.343 回答