我有一组像这样的 lambda
t => t.FirstName
t => t.LastName
t => t.Profession
我想找到一种方法来构建一个表达式,该表达式可以在 Linq to Entities 的Where语句中使用,其中这些 lambda 表达式与使用string.contains的值进行比较
// a filter is definded by a lambda and the string to compare it with
var filters = new Dictionary<Expression<Func<Person, string>>, string>();
filters.Add(t => t.FirstName, "Miller");
filters.Add(t => t.Profession, "Engineer");
var filterConstraints = BuildFilterExpression(t => t, filters);
Entities.Persons.Where(filterConstraints).ToList();
public static Expression<Func<TElement, bool>> BuildFilterExpression<TElement>(Dictionary<Expression<Func<TElement, string>>, string> constraints)
{
List<Expression> expressions = new List<Expression>();
var stringType = typeof(string);
var containsMethod = stringType.GetMethod("Contains", new Type[] { stringType });
foreach (var constraint in constraints)
{
var equalsExpression = (Expression)Expression.Call(constraint.Key.Body, containsMethod, Expression.Constant(constraint.Value, stringType));
expressions.Add(equalsExpression);
}
var body = expressions.Aggregate((accumulate, equal) => Expression.And(accumulate, equal));
ParameterExpression p = constraints.First().Key.Parameters.First();
return Expression.Lambda<Func<TElement, bool>>(body, p);
}
我想我在构建表达式树时做了一些非常错误的事情,因为我得到了以下异常: 无效操作异常 - 参数 't' 未绑定在指定的 LINQ to Entities 查询表达式中。
有谁知道如何解决这个问题?