のは、私がモデルを以下していると仮定しましょう:私はこのため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)
持っています。
この作品を作成するにはどうすればよいですか?
あなたはどの暗黙のパラメータを意味するか:あなたが構築しようとしている実際式はと同等のでしょうか? –
@StefanSchmid唯一のものは?あなたがインスタンス上で呼び出すメソッドを呼び出すとき...インスタンスメソッドであれば、 'Any'はそうではありません。' static'メソッドです。したがって、エラーメッセージが示すように、インスタンスを渡してメソッドを呼び出すときには、 'null'を渡す必要があります。 – Servy
あなたは '' 'のように意味します' '' Expression.Call(null、anyMethod、Expression.Constant(compiledExpression); '' '? –