How do I create a cast when creating an Expression tree dynamically?
The problem is, I have a property of type string:
public class Test
{
public string Id { get; set; }
}
And I want to generically create a strongly typed lambda expression representing a delegate which returns an object instead of a string (Expression<Func<T, object>>).
Right now I am doing this:
private static Expression<Func<T, object>> CreateIdQuery()
{
Type type = typeof(T);
PropertyInfo idProperty = type.GetProperty("Id");
ParameterExpression lambdaParam = Expression.Parameter(type, "x");
MemberExpression body = Expression.Property(lambdaParam, idProperty);
LambdaExpression expr = Expression.Lambda(body, lambdaParam);
return (Expression<Func<T, object>>)expr;
}
But it throws an exception in the last line (I cannot cast Expression<Func<Test, string>> to Expression<Func<Test, object>>).
How do i cast the body of the expression (I am presuming the MemberExpression part needs to be cast into an object)?
Use
Expression.Convert(body, typeof(object)).