2011-01-26 78 views
6

我有這個查詢哪些工作,但是當我嘗試在LINQ中寫入等價物時,我得到了生成的不正確的SQL。如何在LINQ中通過SQL查詢編寫select count組?

我的查詢是:

SELECT COUNT(*) 
FROM tableName 
GROUP BY ColumnId 

我試圖寫它:

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

但看在LINQPad它產生SQL:

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

我是什麼做錯了?謝謝!

回答

18

您的LINQ查詢正在計算組的數量,但您的SQL查詢正在按組生成計數。你想要

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

得到計數的組。

請注意,如果你想要完全一樣的SQL要

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

,因爲它給每個組的ID以及上述第一個例子應該是多一點有用的。

0

嘗試tableName.GroupBy(x => x.ColumnId).Select(x => x.Count())