我試圖創建一個表達式樹,它類似於像進行子查詢:算術運算
SELECT (SELECT Sum(Foo) FROM Bar1) - (SELECT Sum(Foo) FROM Bar2))
我想重用2個表達式樹過於複雜重複。
我現在所擁有的是2(簡體)表達式樹:
Expression<Func<Bar, int>> SumBar1 =
(bar) => (from b in bar.Something
where b.Type = 1
select b).Sum();
Expression<Func<Bar, int>> SumBar2 =
(bar) => (from b in bar.Something
where b.Type = 2
select b).Sum();
我已經嘗試過使用Expression.Subtract
:
Expression foo = Expression.Subtract(SumBar1, SumBar2);
這失敗,出現錯誤:
The binary operator Subtract is not defined for the types 'System.Func
2[Bar,System.Int32]' and 'System.Func
2[Bar,System.Int32]'.
我也嘗試使用Expression.Invoke
調用樹木:
Expression.Subtract( Expression.Invoke(SumBar1,Expression.Parameter(typeof(Bar)), Expression.Invoke(SumBar2,Expression.Constant(typeof(Bar))));
但後來我得到:
The LINQ expression node type 'Invoke' is not supported in LINQ to Entities.
有什麼辦法來組合這兩個表達式樹成一個新的樹,減去他們,並沿參數傳遞?
非常感謝! – 2010-10-22 15:27:38