public async Task <List <StudentDto> > GetStudents(GetStudentsFilter filter) { GetStudentsFilter = filter; await Task.CompletedTask; return(Students); }
public async Task <List <StudentDto> > GetStudents(GetStudentsFilter filter) { var query = students.AsQueryable(); if (filter.NumberOfCourses.HasValue) { query = query.Where(x => x.Enrollments.Count == filter.NumberOfCourses.Value); } if (filter.EnrolledIn.HasValue) { query = query.Where(x => x.Enrollments.Any(e => e.CourseId == filter.EnrolledIn.Value)); } return(await query .Include(x => x.Enrollments) .Select(x => new StudentDto { Id = x.Id, Name = x.Name.Name, Email = x.Email.Address, Enrollments = x.Enrollments.Select(e => new EnrollmentDto { Course = courses .Select(c => new CourseDto { Id = c.Id, Title = c.Title.Title, Credits = c.Credits.Amount, }) .First(c => c.Id == e.CourseId), Grade = e.Grade.ToString(), }).ToList() }) .ToListAsync()); }
public async Task <List <StudentDto> > GetStudents(GetStudentsFilter filter) { using (var conn = Connection) { var query = @" SELECT s.Id, s.Name, s.Email, e.Grade, c.Id as CourseId, c.Title, c.Credits FROM Students s LEFT JOIN Enrollment e ON s.Id = e.StudentId LEFT JOIN Courses c ON e.CourseId = c.Id"; var rows = await conn.QueryAsync <StudentCourseRow>(query); var students = new Dictionary <Guid, StudentDto>(); foreach (var row in rows) { if (!students.ContainsKey(row.Id)) { var student = new StudentDto { Id = row.Id, Name = row.Name, Email = row.Email, }; students.Add(row.Id, student); if (row.CourseId != Guid.Empty) { student.Enrollments.Add(new EnrollmentDto { Course = new CourseDto { Id = row.CourseId, Title = row.Title, Credits = row.Credits, }, Grade = row.Grade }); } } else { students[row.Id].Enrollments.Add(new EnrollmentDto { Course = new CourseDto { Id = row.CourseId, Title = row.Title, Credits = row.Credits, }, Grade = row.Grade }); } } var result = students.Values.ToList(); if (filter.NumberOfCourses.HasValue) { result = result.Where(x => x.Enrollments.Count == filter.NumberOfCourses.Value).ToList(); } if (filter.EnrolledIn.HasValue) { result = result.Where(x => x.Enrollments.Any(e => e.Course.Id == filter.EnrolledIn.Value)).ToList(); } return(result); } }