在表达式树中转换为可空小数

Convert to Nullable Decimal in Expression Trees

我的模型有 Nullable decimal 类型。所以在我的表达式树中它给了我以下错误:

The binary operator Equal is not defined for the types 'System.Nullable`1[System.Decimal]' and 'System.Decimal'

现在我想将字符串转换为十进制?就此而言,我已经尝试过:

decimal? res = Convert.ToDecimal(mystr); // this gives me type as System.Decimal

我也看了this, this, this and this的回答。他们都把它转换成System.Decimal类型,我的表达式树给出了上面提到的错误。

我真的需要将它们转换为 System.Nullable(System.Decimal) 才能为我工作。

我该如何解决?我的模型是从 Entity Framework EDMX 生成的,所以我无法更改它们的类型。我必须在代码中进行转换。

您显示的普通 C# 代码示例 转换为 decimal?,使用从 TT? 的隐式转换任何不可为 null 的值类型 T.

在表达式树中,您只需要使用 Expression.Convert 来执行该转换,例如

// Assuming beforeConversion is an expression tree with a type of
// decimal
var converted = Expression.Convert(beforeConversion, typeof(decimal?));