假设我有以下模型:
public class Department
{
public ICollection<Employee> Employees { get; set; }
}
public class Employee
{
public string Name { get; set; }
}
我想为此构建一个Expression
:
departments.Where(x => x.Employees.Any(y => y.Name.Contains("foo")))
我有以下代码:
var departmentParameterExpression = Expression.Parameter(typeof(Department), "x");
PropertyExpression departmentListProperty = { x.Departments } // Value of the Expression shown in the debugger, actual code is some property helper to get the property by Name
var employeeParameterExpression = Expression.Parameter(typeof(Employee), "y");
PropertyExpression employeeNameProperty = { y.Name } // Same as departmenListProperty
var employeeNameContainsString = Expression.Call(employeeNameProperty, typeof(string).GetMethod("Contains"), Expression.Constant(token));
var compiledExpression = Expression.Lambda<Func<Employee, bool>>(employeeNameContainsString, employeeParameterExpression).Compile();
var anyMethod = typeof(Enumerable).GetMethods(BindingFlags.Static | BindingFlags.Public | BindingFlags.Instance).FirstOrDefault(x => x.Name == "Any" && x.GetParameters().Length == 2 && x.GetGenericArguments().Length == 1).MakeGenericMethod(typeof(Employee));
var containsEmployeeWithSearchString = Expression.Call(departmentListProperty, anyMethod, Expression.Constant(compiledExpression);
运行最后一行,会出现以下错误:
Static method requires null instance, non-static method requires non-null instance. Parameter name: instance
当我刚才.GetMethods(BindingFlags.Static)
时,我不会得到任何Any()
- 方法。
我如何使这项工作?
答案 0 :(得分:5)
Any
和Where
是Enumerable
上的扩展方法,因此根据定义为static
。您尝试构建的实际表达式将等同于:
Enumerable.Where(departments,
x => Enumerable.Any(x.Employees,
y => y.Name.Contains("foo")
)
)
答案 1 :(得分:1)
正如错误消息告诉您的那样,当您调用静态方法时,您无法为要调用的方法提供对象的实例;您需要为隐式参数提供null
。