我动态生成要发送到LINQ to Entities的表达式树。我提供了一个框架,我允许开发人员将输出列指定为lambda表达式。将2个LambdaExpressions合并为1个LamdaExpression
例如,说他们有一列,他们可以指定的方式来拉动值从数据库是:
p => p.Aliases.Count()
和另一列是:
p => p.Names.Where(n => n.StartsWith("hello"))
这里的问题是我需要将这两个组合成一个表达式。
我第一次尝试是:
getter = field.SelectorExpression.Body;
我得到错误信息The parameter 'p' was not bound in the specified LINQ to Entities query expression
因为因为LINQ可以不知道什么P是p.Aliases.Count()
使。
我想接下来的事情是:
getter = Expression.Invoke(field.OrderBySelector, new[] {parameter});
不过,后来我收到消息The LINQ expression node type 'Invoke' is not supported in LINQ to Entities.
,因为,因为我不希望SQL Server来知道如何运行lambda表达式这也令。
现在基本上有这样的表达:
item => new MyClass
{
SomeValue = item.Name, // this was generated from some other code
AnotherValue = item.SomeOtherColumn, // there can be lots of these
AliasCount = p.Aliases.Count() // here of course is the problem
}
显然,我想用“P”来代替表达时,我建立这个与项目表达(我却并知道如何使用) 。
TLDR是否有一种简单的方法可以将LambdaExpression中使用的参数的所有实例替换为另一个表达式?
像http://stackoverflow.com/questions/5430996/replacing-the-parameter-name-in-the-body-of-an-expression/5431309#5431309也许?让我知道,如果这回答它(“访问者”的方法是第一个尝试) – 2011-04-29 19:31:08
你愿意解释它好一点吗?我读了所有,但不明白:/ p => p.Names.Where(n => n.StartsWith(“hello”)) - 是单个表达式,其中单个表达式的参数中的一个参数是另一个表达式表达... – 2011-04-29 19:34:06
Marc Gravell,你简直就是我的男人之神。你回答这个问题比我能把它放在我的代码中并测试它! – tster 2011-04-29 19:40:44