我動態生成要發送到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