我想使用以下 API 生成表达式树:
var managers = dataContext.Employees.Where(e => e.Subordinates.Any());
此外,我如何生成表达式树来执行此操作:
var managedEmployees = managers.ToDictionary(key => key.Manager, value => value.Subordinates.Select(s => s.FullName));
到目前为止,我已经为 .Where() 提出了以下内容,但它出错了,因为它不喜欢 .Where() 中的类型参数new Type[] { typeof(Func<Employee, IEnumerable<Employee>>) }
。
ParameterExpression employeesParameter = Expression.Parameter(typeof(Employee), "e");
MemberExpression subordinatesProperty = Expression.Property(employeesParameter, typeof(Employee).GetProperty("Subordinates"));
MethodCallExpression hasSubordinates = Expression.Call(typeof(Enumerable),
"Any",
new Type[] { typeof(Employee) },
subordinatesProperty);
LambdaExpression whereLambda = Expression.Lambda(hasSubordinates, employeesParameter);
MethodCallExpression whereExpression = Expression.Call(typeof(Queryable),
"Where",
new Type[] { typeof(Func<Employee, IEnumerable<Employee>>) },
dataContext.Employees.AsQueryable(),
whereLambda);