2016-11-22 67 views
0

我在SQL中是正常看似簡單的查詢:轉換條件加盟SQL到LINQ

SELECT table1.Id, count(table2.col) AS OrderCol 
FROM table1 
LEFT JOIN table2 ON table1.Id = table2.Id 
LEFT JOIN table3 ON table2.Id = table3.Id AND table2.condition = 3 //some integer value 
GROUP BY table1.Id 
ORDER BY count(table2.col) DESC 

AND子句中加入出現,我不知道如何將其轉換爲LINQ ..

如何實現它?

回答

-1

試試這個:

var answer = (from t1 in table1 
      join t2 in table2 on t1.Id equals t2.Id into subData1 
      from t2sub in subData1.DefaultIfEmpty() 
      join t3 in table3 on new { Id = t2sub == null ? 0 : t2sub.Id, condition = t2sub == null ? 0 : t2sub.condition } equals new { t3.Id, condition = 3 } into subData 
      from t3sub in subData.DefaultIfEmpty() 
      group new { t1, t2sub } by t1.Id into subGroup 
      orderby subGroup.Count(x => x.t2sub != null) descending 
      select new { 
       Id = subGroup.Key, 
       OrderCol = subGroup.Count(x => x.t2sub != null) 
      }).ToList(); 
+1

需要在第糾正'{t2.Id,t2.condition}'...應該是'{t2sub .Id,t2sub.condition}' – Vikrant

+0

@Vikrant,修正了 –

+0

仍然'對象引用未設置爲對象的實例'錯誤來了 – Vikrant

1

它去是這樣的:

from t1 in db.Table1 
join t2 in db.Table2 on t1.field equals t2.field 
select new { t1.field2, t2.field3}