2017-07-26 78 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#和数据集的课程。再次感谢! –