As a simple example let's assume we have an IQueryable named "myQueryable" with 3 columns Id, Value1 and Value2 and we write the following LINQ expression:
var result = myQueryable.Select(g => new
{
Value1Sum = g.Sum(b => b.Value1),
Value2Sum = g.Sum(b => b.Value2)
});
This will fire 2 different queries, one for each sum and then return both of them as an object like
{ Value1Sum = x , Value2Sum = y }
Is it possible to build the LINQ Expression in such a way that only one query is fired for both sums? After all they are both calculated on the basis of the same dataset..
To make it clearer, I'd expect a query like this:
SELECT SUM(Value1), SUM(Value2) FROM MyTable
but LINQ generates two queries like this(can't post the actual queries fired for security reasons):
exec sp_executesql N'SELECT
[GroupBy1].[A1] AS [C1]
FROM ( SELECT
SUM([Extent1].[Value1]) AS [A1]
FROM [mo].[MyTable] AS [Extent1]) AS [GroupBy1]
..same for Value2. Please note that even if it calls the inner select "GroupBy1" there is no grouping anywhere (also in the actual queries)