I'm trying to create an expression tree that's similar to performing subqueries like:
SELECT (SELECT Sum(Foo) FROM Bar1) - (SELECT Sum(Foo) FROM Bar2))
I'm trying to reuse 2 expression trees that are too complex to repeat.
What I have right now is 2 (simplified) expression trees:
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();
I've already tried to use Expression.Subtract
:
Expression foo = Expression.Subtract(SumBar1, SumBar2);
This fails with the error:
The binary operator Subtract is not defined for the types 'System.Func
2[Bar,System.Int32]' and 'System.Func
2[Bar,System.Int32]'.
I also tried using Expression.Invoke
to call the trees:
Expression.Subtract( Expression.Invoke(SumBar1, Expression.Parameter(typeof(Bar)), Expression.Invoke(SumBar2, Expression.Constant(typeof(Bar))));
But then I get:
The LINQ expression node type 'Invoke' is not supported in LINQ to Entities.
Is there any way to combined the two expression trees into a new tree, subtracting them, and passing along the parameter?