I want to create an expression for converting a property from an Enum to an Int. I want to use DynamicExpressionParser.ParseLambda to parse nested properties:
public enum MyEnum { A, B };
public class OuterClass
{
public InnerClass Inner { get; set; }
public MyEnum Enum { get; set; }
}
public class InnerClass
{
public MyEnum Enum { get; set; }
}
DynamicExpressionParser.ParseLambda<OuterClass, int>(null, true, "Inner.Enum");
But this will throw an exception: Expression of type 'Int32' expected (at index 0)
How can I convert the Enum to an integer inside the expression?
It works with the following method, but i cannot use nested properties there, so it will only work when I place the "Enum" property on the OuterClass:
public static Expression<Func<T, TProperty>> GetExpression<T, TProperty>(string propertyName)
{
// x =>
var parameter = Expression.Parameter(typeof(T));
// x.Name
var mapProperty = Expression.Property(parameter, propertyName);
// (object)x.Name
var convertedExpression = Expression.Convert(mapProperty, typeof(TProperty));
// x => (object)x.Name
return Expression.Lambda<Func<T, TProperty>>(convertedExpression, parameter);
}
GetExpression<OuterClass, int>("Enum");
I found a solution: