2009-10-08 54 views
2

如何將以下SQL語句轉換爲LinqToSQL?將SQL轉換爲linq-to-sql(子查詢)

select t1.name, (select COUNT(*) from table2 where t2.f_id = t1.id) as cnt 
from table1 t1 

我的嘗試似乎最終做了一個內部連接(因此給出了非常不準確的結果)。

感謝

+0

我結束了調用存儲過程做到這一點。我不能相信這樣一個簡單的查詢在LinqToSQL中很難做到! – user9659 2009-10-09 08:11:04

回答

3

如果關係存在於你的數據庫,你可以使用類似於下面的一個非常簡單的查詢:

var results = from t1 in context.Table1 
       select new 
       { 
        t1.Name, 
        T2Count = t1.Table2s.Count() 
       }; 

如果關係不存在,這應該工作:

var results = from t1 in context.Table1 
       join t2 in context.Table2 on t1.id equals t2.f_id into joined 
       select new 
       { 
        t1.Name, 
        T2Count = joined.Count() 
       }; 
+0

我也檢查了生成的Sql(在LinqPad中),它應該與您希望複製的Sql幾乎相同。 – 2009-11-03 21:44:53

+0

謝謝 - 這很容易(和明顯),我認爲它應該是! – user9659 2009-11-04 13:49:52

0

EDIT2:

試試這個,第一個查詢固定的關鍵問題,而第二個現在創建一個正確空的結果。

var subQuery = from t2 in DataContext.Table2 
       group t2 by t2.f_Id into myGroup 
       select new { Id = myGroup.Key, Cnt = myGroup.Count() }; 


var result = from t1 in DataContext.Table1 
      join t2 in subQuery on t1.Id equals t2.Id into temp 
      from t3 in temp.DefaultIfEmpty(new { Id = t1.Id, Cnt = 0 }) 
      select new { t1.Name, t3.Cnt }; 
+0

它很接近,但是這隻返回t1中存在關聯記錄的t2中的行,而問題中的SQL語句包含來自t1的所有條目。 – user9659 2009-10-08 08:56:18

+0

我不得不修改subquery以在group語句之後包含一個額外的from子句。一旦完成,代碼將編譯,但在執行第二個查詢(它試圖將null分配給Int32時)時會引發InvalidOperationException。 – user9659 2009-10-08 11:02:54

+0

查詢編譯但嘗試訪問結果集上的任何方法會生成NotSupportedException:用於查詢運算符'DefaultIfEmpty'的不受支持的重載。 – user9659 2009-10-08 12:16:51

0
var result = db.table1s.select(t => new {.Name = t.Name, .Count = t.table2s.Count()});