プリミティブ値が与えられた場合、age
次のような式を作成する方法を知っています。
//assuming: age is an int or some other primitive type
employee => employee.Age == age
これを行うことにより:
var entityType = typeof(Employee);
var propertyName = "Age";
int age = 30;
var parameter = Expression.Parameter(entityType, "entity");
var lambda = Expression.Lambda(
Expression.Equal(
Expression.Property(parameter, propertyName),
Expression.Constant(age)
)
, parameter);
問題のプロパティと定数がプリミティブ型ではないシナリオを除いて、これは正常に機能します。
比較がオブジェクト間である場合、同様の式をどのように構築しますか?
EF を使用すると、次のように書くことができます。
Location location = GetCurrentLocation();
employees = DataContext.Employees.Where(e => e.Location == location);
それも機能しますが、同じ式を作成しようとすると:
var entityType = typeof(Employee);
var propertyName = "Location";
var location = GetCurrentLocation();
var parameter = Expression.Parameter(entityType, "entity");
var lambda = Expression.Lambda(
Expression.Equal(
Expression.Property(parameter, propertyName),
Expression.Constant(location)
)
, parameter);
次のようなエラーが表示されます。
Unable to create a constant value of type 'Location'. Only primitive types or enumeration types are supported in this context.
私の疑いは、Expression.Constant()
プリミティブ型のみを期待しているため、別の式ファクトリ メソッドを使用する必要があるということです。(もしかしてExpression.Object
? - 私はそれが存在しないことを知っています)
オブジェクトを比較する式を作成する方法はありますか? コンパイルされた LINQ ステートメントの場合は EF が正しく解釈できるのに、式の場合は解釈できないのはなぜですか?