Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating dynamic Expression<Func<T,Y>>

Tags:

c#

.net

linq

I want to create a dynamic Expression<Func<T,Y>>. Here is the code which works for string but doesn't work for DateTime. By doesn't work I mean, I get this exception:

"Expression of type 'System.Nullable`1[System.DateTime]' cannot be used for return type 'System.Object'"

Can anybody analyze the mistake?

        Type type = typeof(DSVPNProjection);
        ParameterExpression arg = Expression.Parameter(type, "x");
        Expression expr = arg;

        PropertyInfo propertyInfo = type.GetProperty(sidx);
        expr = Expression.Property(expr, propertyInfo);

        var expression = 
        Expression.Lambda<Func<DSVPNProjection, object>>(expr, arg);

Do I need to change the object to some other type? If yes, then which? As you can see I am trying to dynamically fetch the PropertyInfo and use that as the 2nd parameter in Func.

like image 904
TCM Avatar asked Mar 25 '12 13:03

TCM


People also ask

Can we use dynamic in lambda expressions?

In 2010, the Dynamic Type was introduced and that gave us the ability to create dynamic lambda expressions.

What is Expression tree in LINQ?

You can compile and run code represented by expression trees. This enables dynamic modification of executable code, the execution of LINQ queries in various databases, and the creation of dynamic queries. For more information about expression trees in LINQ, see How to use expression trees to build dynamic queries (C#).


1 Answers

For value types, you need to perform the boxing explicitly (i.e. convert to Object):

    Type type = typeof(DSVPNProjection);
    ParameterExpression arg = Expression.Parameter(type, "x");
    Expression expr = null;

    PropertyInfo propertyInfo = type.GetProperty(sidx);
    expr = Expression.Property(arg, propertyInfo);
    if (propertyInfo.PropertyType.IsValueType)
        expr = Expression.Convert(expr, typeof(object));

    var expression = 
    Expression.Lambda<Func<DSVPNProjection, object>>(expr, arg);
like image 179
Thomas Levesque Avatar answered Oct 05 '22 02:10

Thomas Levesque