我正在为数据库查询动态构建Lambda表达式(使用LINQ)。我有一个用户提供的字符串(例如" 80"),我需要与我的数据库实体对象(例如Car.Mileage)中的字段进行比较。当我尝试构建比较表达式时,我得到一个类型错误。
Car.Mileage声明如下:
public Nullable<int> Mileage
我以这种方式构建我的查询:
Nullable<int> userProvided = Int32.parse(arg);
Expression constant = Expression.Constant(userProvided);
Expression property = Expression.Property(car, "Mileage");
Expression exp = Expression.Equal(property, constant);
这会导致错误:
没有为类型定义Expression.Equal &#39; System.Nullable`1 [System.Int32]&#39;和&#39; System.Int32&#39;。
我尝试了一些方法来转换用户的论点,却没有取得多大成功。
答案 0 :(得分:0)
弄清楚,主要是重新阅读this post。
我必须使用Expression.Convert和属性Expression的类型:
Expression.Equal(property, Expression.Convert(constant, ((MemberExpression)property).Type));