Convert.ChangeType 上出现错误,Nullable

本文关键字:Nullable Int32 错误 ChangeType Convert | 更新日期: 2023-09-27 18:37:17

我正在为数据库查询动态构建 Lambda 表达式(使用 LINQ)。我有一个用户提供的字符串(例如"80"),我需要将其与数据库实体对象(例如 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"。

我尝试了几种方法来转换用户的论点,但没有取得多大成功。

  • Convert.ChangeType(constant, typeof(Car.Mileage)) 失败,因为 Mileage 的类型是 RuntimePropertyInfo。(来源)
  • 我已经尝试了 Expression.Convert 如此处和此处所述,但无法让它工作。

Convert.ChangeType 上出现错误,Nullable<Int32>

弄清楚,主要是通过重新阅读这篇文章。

我不得不使用Expression.Convert与属性Expression的类型:

Expression.Equal(property, Expression.Convert(constant, ((MemberExpression)property).Type));
相关文章: