将SQL原始查询转换为Linq

时间:2018-09-23 06:33:20

标签: linq sql-to-linq-conversion

我有3个表(活动,参与者和注册),我想知道每个参与者参加的活动数量。我是编写SQL Linq查询的新手,请帮助我将下面的查询转换为Linq。

Select count(Activities.ActivityId) AS NO_Activities,Activities.ActivityId,Enrollments.PostTestScore1
from Participants,Activities,Enrollments
where Participants.ParticipantId=Enrollments.ParticipantId
    and Activities.ActivityId=Enrollments.ActivityId
    and Enrollments.ParticipantId= 2883
    Group By Enrollments.PostTestScore1,Activities.ActivityId;

谢谢

2 个答案:

答案 0 :(得分:2)

var query = from a1 in Activities
            join e1 in Enrollments on a1.ActivityId equals e1.ActivityId
            join p1 in Participants on e1.ParticipantId equals p1.ParticipantId
            where e1.ParticipantId= 2883
            group new { e1, a1 }
            by new { e1.PostTestScore1, a1.ActivityId } into g
            select new
            {
                 ActivityId = g.Key.ActivityId,
                 PostTestScore1 = g.Key.PostTestScore1,
                 NO_Activities = g.Count()
            };

答案 1 :(得分:2)

我使用Lambda查询找到了答案,如下所示。

var no_ctivities = db.Activities
               .Join(
                   db.Enrollments,
                   ac => ac.ActivityId,
                   en => en.ActivityId,
                   (enr, act) => new { en = enr, ac = act })
               .Join(
                   db.Participants.Where(pr => pr.ParticipantId == id),
                   en => en.ac.ParticipantId,
                   prt => prt.ParticipantId,
                   (enr, prt) => new { enr.ac.PostTestScore1, enr.ac.PostTestScore2, enr.ac.ActivityId, enr.ac.AttendFirstday, enr.ac.AttendSecondDay })
               .Select(c => new
               {
                   c.ActivityId,
                   c.PostTestScore1,
                   c.PostTestScore2,
                   c.AttendFirstday,
                   c.AttendSecondDay
               }).count();