How to convert a LambdaExpression to typed Expression<Func<T, T>>
Asked Answered
D

1

25

I'm dynamically building linq queries for nHibernate.

Due to dependencies, I wanted to cast/retrieve the typed expression at a later time, but I have been unsuccessfull so far.

This is not working (the cast is supposed to happen elsewhere):

var funcType = typeof (Func<,>).MakeGenericType(entityType, typeof (bool));
var typedExpression =  (Func<T, bool>)Expression.Lambda(funcType, itemPredicate, parameter); //Fails

This is working:

var typedExpression = Expression.Lambda<Func<T, bool>>(itemPredicate, parameter);

Is it possible to get the 'encapsulated' typed expression from a LambdaExpression?

Durning answered 25/4, 2013 at 11:1 Comment(2)
maybe you are looking for typedExpression.Compile()Walston
I need to use the expression as an IQueryable with my ORM mapper so it can not be compiled.Durning
S
34
var typedExpression =
    (Func<T, bool>)Expression.Lambda(funcType, itemPredicate, parameter); //Fails

This is not surprising, as you have to Compile a LambdaExpression in order to get an actual delegate that can be invoked (which is what Func<T, bool> is).

So this would work, but I 'm not sure if it is what you need:

// This is no longer an expression and cannot be used with IQueryable
var myDelegate =
    (Func<T, bool>)
    Expression.Lambda(funcType, itemPredicate, parameter).Compile();

If you are not looking to compile the expression but instead to move an expression tree around, then the solution is to instead cast to an Expression<Func<T, bool>>:

var typedExpression = (Expression<Func<T, bool>>) 
                      Expression.Lambda(funcType, itemPredicate, parameter);
Syllogize answered 25/4, 2013 at 11:9 Comment(4)
Thanks for reply. Yes I'm looking to move the expression tree around. The problem is the cast which you're refering to Expression<Func<T, bool>> typedExpression = Expression.Lambda(funcType, itemPredicate, parameter); This results in Cannot convert souce type System.Linq.Expressions.LambdaExpression to target type System.Linq.Expressions.Expression<System.Func<MyType, object>>Durning
@Larantz: Sorry, my mistake; I forgot that you need to cast explicitly. Check out the updated answer.Syllogize
Thank you. I can not belive how blind I was not to notice that I was lacking the Expression<> part of the cast :).Durning
Explicit cast var typedExpression = (Expression<Func<T, bool>>) (...) solved my similar issue.Distinction

© 2022 - 2024 — McMap. All rights reserved.