次の 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() についてこれまでに次のことを思いつきましたが、 の型パラメーターが気に入らないためエラーになります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);