2013-04-25 208 views
15

我正在为nHibernate动态构建linq查询。如何将LambdaExpression转换为键入的表达式<Func<T, T>>

由于依赖关系,我想在以后的时间输入/检索类型化表达式,但到目前为止我一直没有成功。

这不是工作(中投应该在别处发生):

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

这是工作:

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

是否有可能得到“封装”从LambdaExpression输入表达式?

+0

也许你正在寻找typedExpression.Compile() – jure 2013-04-25 11:07:04

+1

我需要使用表达式作为一个IQueryable与我的ORM映射器,因此它不能被编译。 – Larantz 2013-04-26 07:52:53

回答

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

这并不奇怪,因为你为了获得可以调用的实际委托(这是什么Func<T, bool>是)必须Compile一个LambdaExpression

所以这会工作,但我不知道这是否是你所需要的:

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

如果你不希望编译表达式,而是四处移动的表达式目录树,那么解决方案是改为强制转换为Expression<Func<T, bool>>

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

感谢您的回复。 是的我正在寻找移动表达式树。 问题是你正在引用的表达式类型表达式= Expression.Lambda(funcType,itemPredicate,parameter);'这会导致 '无法将源类型System.Linq.Expressions.LambdaExpression转换为目标类型System.Linq.Expressions.Expression >' – Larantz 2013-04-26 06:44:29

+0

@Larantz:对不起,我的错误;我忘了你需要明确施放。查看更新后的答案。 – Jon 2013-04-26 08:22:25

+1

谢谢。 我不能相信我是多么的盲目,我没有注意到我缺少表演<>部分演员:)。 – Larantz 2013-04-26 10:45:28

相关问题