![](/img/trans.png)
[英]Convert.ChangeType throwing Invalid Cast Exception for nullable int
[英]Error on Convert.ChangeType with Nullable<Int32>
我正在为数据库查询动态构建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);
这会导致错误:
未为类型'System.Nullable'1 [System.Int32]'和'System.Int32'定义Expression.Equal。
我尝试了几种方法来转换用户的参数,但没有成功。
找出答案,主要是通过重新阅读这篇文章 。
我必须将Expression.Convert与属性Expression的类型一起使用:
Expression.Equal(property, Expression.Convert(constant, ((MemberExpression)property).Type));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.