How to write a select count group by SQL query in LINQ?

匿名 (未验证) 提交于 2019-12-03 08:46:08

问题:

I have this query which works but when I try to write the equivalent in LINQ I get the incorrect SQL produced.

My query is:

SELECT COUNT(*) FROM tableName GROUP BY ColumnId 

I've tried writing it as:

tableName.GroupBy(x => x.ColumnId).Count() 

But looking in LINQPad it is producing the SQL:

SELECT COUNT(*) AS [value] FROM ( SELECT NULL AS [EMPTY] FROM [tableName] AS [t0] GROUP BY [t0].[ColumnId] ) AS [t1] 

What am I doing wrong? Thanks!

回答1:

Your LINQ query is counting the number of groups but your SQL query is producing the counts by group. You want

var counts = tableName.GroupBy(x => x.ColumnId)                       .Select(g => new { g.Key, Count = g.Count() }); 

to get the counts by group.

Note that if you want exactly the same SQL you want

var counts = tableName.GroupBy(x => x.ColumnId)                       .Select(g => g.Count()); 

The first example above should be a little more useful as it gives the ids of each group as well.



回答2:

Try tableName.GroupBy(x => x.ColumnId).Select(x => x.Count())



标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!