Convert to Nullable Decimal in Expression Trees

My models have Nullable decimal types. So in my Expression trees it gave me the following error:

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

Now I want to convert a string to decimal? and for that matter I have tried as:

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

I have also looked to the answers of this, this, this and this. They all convert it into type System.Decimal and my expression trees gave the error mentioned above.

I really need to convert them to System.Nullable(System.Decimal) to work for me.

How can I work it out? My models are generated from Entity Framework EDMX so I cannot change their types. I have to do the conversion in the code.

Jon Skeet
people
quotationmark

The normal C# code example you've shown has converted to decimal?, using the implicit conversion from T to T? for any non-nullable value type T.

In an expression tree, you just need to use Expression.Convert to perform that conversion, e.g.

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

people

See more on this question at Stackoverflow