2016-12-20 2 views
3

のは、私がモデルを以下していると仮定しましょう:私はこのためExpressionを構築したい

public class Department 
{ 
    public ICollection<Employee> Employees { get; set; } 
} 

public class Employee 
{ 
    public string Name { get; set; } 
} 

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

私はちょうど私が、残念ながら任意のAny()方法 - を得ることはありません.GetMethods(BindingFlags.Static)持っています。

この作品を作成するにはどうすればよいですか?

答えて

1

エラーメッセージが示すとおり、静的メソッドを呼び出すときは、呼び出すメソッドのオブジェクトのインスタンスを指定することはできません。暗黙のパラメーターにはnullを指定する必要があります。

+1

あなたはどの暗黙のパラメータを意味するか:あなたが構築しようとしている実際式はと同等のでしょうか? –

+0

@StefanSchmid唯一のものは?あなたがインスタンス上で呼び出すメソッドを呼び出すとき...インスタンスメソッドであれば、 'Any'はそうではありません。' static'メソッドです。したがって、エラーメッセージが示すように、インスタンスを渡してメソッドを呼び出すときには、 'null'を渡す必要があります。 – Servy

+0

あなたは '' 'のように意味します' '' Expression.Call(null、anyMethod、Expression.Constant(compiledExpression); '' '? –

5

AnyおよびWhereは、Enumerable上の拡張メソッドであり、定義上、staticです。

Enumerable.Where(departments, 
       x => Enumerable.Any(x.Employees, 
            y => y.Name.Contains("foo") 
            ) 
       )