Hi all, i am investigating into the way LINQ gets mapped to SQL, and I have some troubles getting a simple thing.
There is a table sessions
that holds one row per user login. Consider the following SQL
SELECT COUNT(*) AS c
FROM sessions
GROUP BY sessions.user_id
ORDER BY c DESC
I am using LINQPad to test LINQ-to-SQL transformations.
The strait-forward
from s in Sessions group s by s.User_id into logins
orderby logins.Count() descending
select new { c = logins.Count() }
gives me
SELECT [t1].[value2] AS [c]
FROM (
SELECT COUNT(*) AS [value], COUNT(*) AS [value2]
FROM [sessions] AS [t0]
GROUP BY [t0].[user_id]
) AS [t1]
ORDER BY [t1].[value] DESC
The modified
(from s in Sessions group s by s.User_id into logins
select new { c = logins.Count() }).OrderByDescending(v => v.c)
gets mapped to
SELECT [t1].[value2] AS [c]
FROM (
SELECT COUNT(*) AS [value], COUNT(*) AS [value2]
FROM [sessions] AS [t0]
GROUP BY [t0].[user_id]
) AS [t1]
ORDER BY [t1].[value] DESC
I just can't get this optimal output. Is there a way?
Or, maybe, I shouldn't be concerned as the SQL will get optimized anyway?