0
我为数据库查询(使用LINQ)动态构建Lambda表达式。我有一个用户提供的字符串(例如“80”),我需要与我的数据库实体对象(例如Car.Mileage)中的字段进行比较。当我尝试构建比较表达式时,出现类型错误。Convert.ChangeType with Nullable错误<Int32>
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 is not defined for the types 'System.Nullable`1[System.Int32]' and 'System.Int32'.
我我尝试了几种方法来转换用户的观点,但没有取得太大的成功。
- Convert.ChangeType(constant,typeof(Car.Mileage))失败,因为里程的类型是RuntimePropertyInfo。 (Source)
- 我已经尝试过Expression.Convert,如here和here所述,但尚未能使其正常工作。
有什么意义? Int32.Parse()不生成可空。 –
@hans它不生成可为空,但Expression.Equal()抱怨如果一个参数是可以为空而另一个不是。 –