我们假设我有以下模型:
public class Department
{
public ICollection<Employee> Employees { get; set; }
}
public class Employee
{
public string Name { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
我想为此建立一个Expression:
departments.Where(x => x.Employees.Any(y => y.Name.Contains("foo")))
Run Code Online (Sandbox Code Playgroud)
我有以下代码:
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);
Run Code Online (Sandbox Code Playgroud)
运行最后一行,给出了以下错误:
Static method requires null instance, non-static method requires non-null instance. Parameter name: instance
当我刚才.GetMethods(BindingFlags.Static)没有得到任何Any()-Method不幸.
我该如何工作?
Any并且Where是扩展方法Enumerable,因此是static定义.您尝试构建的实际表达式将等效于:
Enumerable.Where(departments,
x => Enumerable.Any(x.Employees,
y => y.Name.Contains("foo")
)
)
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
156 次 |
| 最近记录: |