如何简化linq到sql查询?

时间:2016-06-29 06:24:35

标签: c# sql-server linq

我刚刚写了一个linq到sql查询,它带来了入选的学生在选定的学期中获得最高分,它只是工作正常。但是查询有点难以理解。

from enrollment in _enrollmentRepository.GetAll()
 .WhereIf(!input.TermId.HasValue, x => x.Class.Term.IsCurrent)
 .WhereIf(input.TermId.HasValue, x => x.TermId == input.TermId.Value)
 .WhereIf(input.CourseId.HasValue, x => x.Class.CourseId == input.CourseId.Value)

join student in _studentRepository.GetAll().Include(x => x.User) on enrollment.StudentId equals student.Id into students
from student in students
join grade in _gradeRepository.GetAll().Where(x => !x.Exam.IsDeleted && !x.Exam.Term.IsDeleted)
on student.Id equals grade.StudentId into grades

join admissionStudent in _studentAdmissionRepository.GetAll()
.Where(x => x.GradeLevelId == (int)GradeLevel.PrepSchool && (x.AdmissionStatusId == (int)AdmissionStatus.Active || x.AdmissionStatusId == (int)AdmissionStatus.OnHold) && x.Type == (int)EnrollmentType.Default)
on student.Id equals admissionStudent.StudentId
into admissionStudents
select new
{
    Id = student.Id,
    FirstName = student.User.Name,
    LastName = student.User.Surname,
    UserName = student.User.UserName,
    ClassId = enrollment.ClassId,
    ClassName = enrollment.Class.Term.Name + " " + enrollment.Class.Course.Name + " " + enrollment.Class.SectionName,
    TermId = enrollment.TermId,
    CourseId = enrollment.Class.CourseId,
    TermName = enrollment.Class.Term.Name,
    CourseName = enrollment.Class.Course.Name,
    DepartmentName = admissionStudents.FirstOrDefault().AdmissionType.Department.Name,
    Grades = grades.Select(x => new
    {
        Point = x.Point,
        Percentage = x.Exam.Percentage,
        MaxPoint = x.Exam.MaxPoint,
        CourseId = x.Exam.CourseId,
        TermId = x.Exam.TermId
    }).ToList(),
    TotalEarned = grades.Count() == 0 ? 0 : grades.Sum(y => y.Exam == null ? 0 : (y.Point ?? 0) * (y.Exam.MaxPoint / y.Exam.Percentage)),
    TotalPoint = grades.Count() == 0 ? 0 : grades.Sum(y => y.Exam == null ? 0 : y.Exam.Percentage),
}).ToList().GroupBy(x => x.TermId).Select(y => new
{
    TermId = y.Key,
    TermName = y.FirstOrDefault().TermName,

    Courses = y.GroupBy(x => x.CourseId).Select(x => new
    {
        CourseName = x.FirstOrDefault().CourseName,
        StudentWithGrades = x.Select(t => new
        {
            Id = t.Id,
            FirstName = t.FirstName,
            LastName = t.LastName,
            UserName = t.UserName,
            ClassName = t.ClassName,
            ClassId = t.ClassId,
            Grades = t.Grades,
            TotalEarned = t.Grades.Count() == 0 ? 0 : t.Grades.Where(z => z.TermId == t.TermId && z.CourseId == t.CourseId).Sum(f => (f.Point ?? 0) * (f.Percentage / f.MaxPoint)),
            DepartmentName = t.DepartmentName
        })
    }).ToList()
}).ToList()

如何简化此查询?

0 个答案:

没有答案