2012-02-19 165 views
0

我想運行一個linq查詢,該查詢將返回值到我的自定義DTO。這個特定的linq查詢將需要考慮來自多個表的聯接,使用switch case語句,count(*)和Linq查詢與表連接,case語句,count,group by子句

這是查詢的SQL版本示例,我將需要LinQ等效項...

select 
slm.SLType, 
count(c.EStatID) as EStat, 
COUNT(cpd.TrId) as Training, 
COUNT(
CASE WHEN cpd.TrStat= 44 THEN 1 
    WHEN cpd.TrStat!= 44 THEN NULL 
    WHEN cpd.TrStat IS NULL THEN NULL 
END) as TrainingComplete, 
COUNT(
CASE WHEN cpd.CndAssess = 44 THEN 1 
    WHEN cpd.CndAssess != 44 THEN NULL 
    WHEN cpd.CndAssess IS NULL THEN NULL 
END) as AssessmentComplete 
from TabC c , TabCPD cpd, TabSLM slm 
where cpd.SLid = slm.SLid 
and c.Id= cpd.CID 
and c.O_Id = 1 
group by slm.SLType 

它以下列格式返回記錄。我將每條記錄都放在一個換行符中,並用逗號分隔。下面的數字只是作爲一個例子

TypeA, 0 , 1 , 1, 0 
TypeB, 1 , 0 , 1, 0 

我試圖創建類似下面的一個沒有多少運氣的格式LINQ查詢

MyCustomTableC_DTO將在每個字段屬性查詢。任何想法如何做到這一點?查詢我將用它來建立類型的列表MyCustomTableC_DTO

感謝您的時間...

+2

您可以將表前綴('c.','cpd.','slm.')添加到您的查詢中,以便我們知道哪個列屬於哪個表? – Diego 2012-02-19 19:24:24

+0

完成。編輯的問題。 – user20358 2012-02-19 19:55:42

回答

7

當您嘗試SQL語句轉換成逐行LINQ線,你會得到這樣的事情:

from row in (
    from c in db.TabC 
    from cpd in db.TabPD 
    from slm in db.TabSLM 
    where cpd.SLid == slm.SLid 
    where c.Id == cpd.CID 
    where c.O_Id == 1 
    select new { c, cpd, slm }) 
group row in row.slm.SLType into g 
select new 
{ 
    SLType = g.Key, 
    EStat = g.Count(r => r.c.EstatID != null), 
    Training = g.Count(r => r.cpd.TrId != null), 
    TrainingComplete = 
     g.Count(r => r.cpd.TrStat == 44), 
    AssessmentComplete = 
     g.Count(r => r.cpd.CndAssess == 44) 
}; 

然而,這個查詢使得事情變得複雜化並且完全忽略了Entity Framework對這個模型有更多的瞭解並且生成所有外鍵作爲實體屬性的事實。除此之外,使用LINQ,你必須經常以相反的方式來處理事情。例如,在你的情況下,不要從TabCTabSLM實體開始,而是從TabPD開始,因爲該表是交叉表。有了這些知識,我們可以寫LINQ查詢是這樣的:

from cpd in db.TabCPDs 
where cpd.TabC.O_Id == 1 
group cpd by cpd.TabSLM.SLType into g 
select new 
{ 
    SLType = g.Key, 
    EStat = g.Count(r => r.TabC.EstatID != null), 
    Training = g.Count(r => r.TrId != null), 
    TrainingComplete = 
     g.Count(r => r.TrStat == 44), 
    AssessmentComplete = 
     g.Count(r => r.CndAssess == 44)   
}; 

這是更簡單,(如果我沒有弄錯)具有相同的效果。

+0

我需要在db.TabSLM中將slm連接到slm。你將如何修改這個查詢呢? – user20358 2012-03-26 15:28:00

+0

標記我爲答案,並在SO上發佈一個新問題。 – Steven 2012-03-26 17:17:22