Search code examples
linqsql-to-linq-conversion

Convert SQL raw query into Linq


I have 3 tables (activities, participants and enrollments) and I want to know the number of activities that each participant participated into.I am new in writing SQL Linq query please help me to convert the below query into 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;

Thanks


Solution

  • I found the answer using Lambda query as below.

    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();