我有这段代码:
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"
当我将这个谓词与Entity Framework一起使用但不能与NHiernate一起使用时,我没有任何问题。我认为问题是“真实”。是否可以在没有“真实”的情况下创建此谓词?
答案 0 :(得分: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);