我想将SQL查询转换为LINQ查询

时间:2015-04-03 13:26:01

标签: c# sql linq group-by sql-to-linq-conversion

这是我的SQL查询

SELECT a.CLASS_ID,a.ACTIVITY_TYPE_ID,COUNT(*) 
FROM AIS.CLASS_ASSESSMENT_DATE_INFO a 
WHERE a.CLASS_ID =22222
GROUP by a.CLASS_ID,a.ACTIVITY_TYPE_ID

我想将此查询转换为linq查询。你能救我吗?

2 个答案:

答案 0 :(得分:1)

试试这个: -

var result = db.CLASS_ASSESSMENT_DATE_INFO.Where(x => x.CLASS_ID == 22222)
               .GroupBy(x => new { x.CLASS_ID, x.ACTIVITY_TYPE_ID })
               .Select(x => new 
                         {
                            CLASS_ID = x.Key.CLASS_ID,
                            ACTIVITY_TYPE_ID = x.Key.ACTIVITY_TYPE_ID,
                            Count = x.Count()          
                         });

或者如果您更喜欢query syntax: -

var result = from x in db.CLASS_ASSESSMENT_DATE_INFO
             where x.CLASS_ID == 22222
             group x by new { x.CLASS_ID, x.ACTIVITY_TYPE_ID } into g
             select new 
                         {
                            CLASS_ID = g.Key.CLASS_ID,
                            ACTIVITY_TYPE_ID = g.Key.ACTIVITY_TYPE_ID,
                            Count = g.Count()          
                         };

答案 1 :(得分:0)

 var q = from a in AIS.CLASS_ASSESSMENT_DATE_INFO
         where a.CLASS_ID == 22222
         group a by new{
           a.CLASS_ID,
           a.ACTIVITY_TYPE_ID} into g
         select new{
           CLASS_ID = g.Key.CLASS_ID,
           ACTIVITY_TYPE_ID = g.Key.ACTIVITY_TYPE_ID,
           Count = g.Count()
         };