使用Linq使用链接记录计数来模拟SQL查询

时间:2014-03-11 14:45:12

标签: c# sql linq

在SQL中,我会做类似的事情:

    SELECT SVSSurvey_Level.ID, SVSSurvey_Level.SurveyID,
           SVSSurvey_Level.UserCode, SVSSurvey_Level.ExternalRef,
           SVSSurvey_Level.Description, SVSSurvey_Level.ParentLevelID,
           SVSSurvey_Level.LevelSequence, SVSSurvey_Level.Active, 
           COUNT(SVSSurvey_Question.ID) AS Questions
    FROM SVSSurvey_Level LEFT OUTER JOIN
         SVSSurvey_Question ON SVSSurvey_Level.ID = SVSSurvey_Question.LevelID
    GROUP BY SVSSurvey_Level.ID, SVSSurvey_Level.SurveyID,
             SVSSurvey_Level.UserCode, SVSSurvey_Level.ExternalRef,
             SVSSurvey_Level.Description, SVSSurvey_Level.ParentLevelID,
             SVSSurvey_Level.LevelSequence, SVSSurvey_Level.Active

在相关的Linq查询中,我有:

var levels = (from l in dataContext.SVSSurvey_Levels 
              where l.SurveyID == intSurveyId
              orderby l.LevelSequence 
              select new Level
              {
                  Id = l.ID,
                  SurveyId = l.SurveyID,
                  UserCode = l.UserCode ,
                  ExternalRef = l.ExternalRef ,
                  Description = l.Description ,
                  ParentLevelId = (l.ParentLevelID),
                  LevelSequence = ( l.LevelSequence ),

                  Active = Convert .ToBoolean( l.Active )
              });

如何添加类似的链接记录数(相当于上例中的COUNT(SVSSurvey_Question.ID) AS Questions)?

2 个答案:

答案 0 :(得分:1)

这不够吗?假设QuestionCount是您级别中的属性,并且您在模型中正确设置了导航属性。

QuestionCount = l.SVSurvey_Questions.Count(),

答案 1 :(得分:0)

您可以在“问题”表格上执行左连接,然后计算非null的所有内容:

var levels = (from l in dataContext.SVSSurvey_Levels
              join q in dataContext.SVSSurvey_Questions on l.ID equals q.LevelID into grp
              from qq in grp.DefaultIfEmpty()
              where l.SurveyID == intSurveyId
              orderby l.LevelSequence 
              select new Level
              {
                  ...
                  ...
                  QuestionCount = (from qq where qq != null select qq).Count()
                  ...
              });