2017-07-26 91 views
0

來自T-SQL,我試圖在示例ASP.Net mvc(c#)程序中使用基本數據集。Linq - 加入表的主鍵

我有三個表,如下面的照片(連接的)中所示:

  1. 類別(PK IdCollection)
  2. 衝刺(PK IdSprint,FK IdCollection)
  3. DeployDocuments(PK IdDeployDocuments,FK IdSprint )

Table relationship diagram

在我的asp.net mvc的續滾子,我想這個簡單查詢的LINQ相當於數據集傳遞給視圖:

SELECT 
c.TxCollectionName 
,s.SprintNumber 
,COUNT(dd.IdDeployDocument) [NumProjects] 
FROM Collections AS c 
JOIN Sprints AS s 
    ON s.IdCollection = c.IdCollection 
LEFT JOIN DeployDocuments AS dd 
    ON dd.IdSprint = s.IdSprint 
GROUP BY 
c.TxCollectionName 
, s.SprintNumber; 

我不能爲我的生活,找出如何做到這一點! 只要我嘗試在linq中創建第二個連接(更不用說左連接)。

我以前只是用:

var CollectionSprints = db.Collections.Include(d => d.Sprints) 

但我需要的所有項目(deployDocuments)以及求和的,所以現在我想起來討價還價的查詢,像這樣:

 var query = from Collections in db.Collections 
       join Sprints in db.Sprints on Collections.IdCollection equals Sprints.IdCollection 
       join DeployDocuments in db.DeployDocuments on DeployDocuments.IdSprint equals Sprints.IdSprint 

但是一旦我開始第二次連接,它會拋出錯誤,我是否應該閱讀linq的限制?我應該採取一種完全不同的方法來解決這個問題嗎?或者我應該只是GTFO並在C#上採取更多課程。

+0

爲什麼你不能使用存儲過程呢?你決定使用LINQ嗎? –

+0

我完全可以使用這個存儲過程,但我還沒有學會如何使用存儲過程與asp.net mvc,但我相信我可以快速學習。這是一個「複雜」的查詢在linq中執行嗎? **編輯:**我猜我的看法有點偏斜,因爲我不習慣爲長度小於10-15行的查詢創建存儲過程,最好的做法是將SP用於所有不是' 「基本」查詢? –

+0

「LEFT JOIN」會變得複雜。我並不是說它不可行,只是在你的關卡中,使用存儲過程可能更容易。 –

回答

1

Linq左連接看起來與SQL左連接有點不同,所以它可能有點混亂。 This SO answer顯示了編寫Linq左連接的簡單方法。 .DefaultIfEmpty()使第二次加入左連接。

這就是我想出了:

var result = (
    from c in Collections 
    from s in Sprints.Where(s => s.IdCollection == c.IdCollection) 
    from dd in DeployDocuments.Where(dd => dd.IdSprint == s.IdSprint).DefaultIfEmpty() 
    select new { c, s, dd }) 
.GroupBy(g => new { g.c.TxCollectionName, g.s.SprintNumber }) 
.Select(s => new { s.Key.TxCollectionName, s.Key.SprintNumber, NumProjects = s.Count() }; 
+0

謝謝,感謝您花時間回答這個問題!它看起來像預期的那樣工作;但是,這讓我意識到我已經有點頭大了,應該只是後退一步,並且一般來說還需要更多的關於c#和數據集的課程。再次感謝! –