开发者

Ambiguous LINQ to SQL mapping

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?


Or, maybe, I shouldn't be concerned as the SQL will get optimized anyway?

Compare the execution plans of the "optimal" sql and the generated sql. (Sql Studio - click on "display estimated execution plan")


By inspection and drawing upon my years of clicking that button - the generated subquery presents no concern at all.

Even this query should be fine (meaning: costs no additional io)

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 


There is "nothing" wrong with that query, it wont COUNT the rows twice if thats what you are worried about.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜