链接linq查询

时间:2016-01-18 23:53:46

标签: c# linq

由于在我的视图中为数据表创建了一个简单的过滤器,因此尝试链接linq查询。

public ActionResult Index(int? courseId, string grade, int? statusId)
    {
        var query = from s in db.Students
                    join e in db.Enrollments on s.ID equals e.ID
                    join c in db.Courses on e.CourseID equals c.ID
                    orderby e.Grade.HasValue descending, e.Grade, s.StatusID
                    select new { s, e, c };           

        if (courseId != null)
        {
            query = query.Where(q => q.e.CourseID == courseId);
        }

        if (!string.IsNullOrEmpty(grade))
        {
            query = query.Where(q => q.e.Grade.Equals(grade));
        }

        if (statusId != null)
        {
            query = query.Where(q => q.s.StatusID == statusId);
        }

        query.Select( q => new ViewModels.ReportView
                {
                    ID = q.s.ID,
                    Name = q.s.FirstName + " " + q.s.LastName,
                    Course = q.c.Title,
                    Grade = q.e.Grade,
                    GraduationDate = q.s.GraduationDate,
                    Status = q.s.Status.Title
                });

Linq强迫您使用select或group结束查询,这迫使我在开始时放置一个不必要的select。由于某种原因,这导致它忽略了最后一个选择,只使用了初始值。

我已尝试通过e.ID进行分组,但这并没有按预期工作......

我确信这很简单,但我迷失了,有什么想法吗?

1 个答案:

答案 0 :(得分:0)

我通常会创建一个辅助函数来简化复杂的linq

   class Test
    {
        public ActionResult Index(int? courseId, string grade, int? statusId)
        {
            var query = from s in db.Students
                        join e in db.Enrollments on s.ID equals e.ID
                        join c in db.Courses on e.CourseID equals c.ID
                        orderby e.Grade.HasValue descending, e.Grade, s.StatusID
                        select QueryResults(courseId, grade, statusId, s, e, c);


        }
        public ViewModels.ReportView QueryResults(int? courseId, string grade, int? statusId, Student student, Enrollments enrollment, Cource course)
        {

            if ((courseId != null) && (courseId != course))
            {
                return null;
            }

            if ((!string.IsNullOrEmpty(grade)) && (grade != enrollment.Grade))
            {
                return null;
            }

            if ((statusId != null) && (statusId != student.StatusID))
            {
                return null;
            }

            return new ViewModels.ReportView
            {
                ID = student.ID,
                Name = student.FirstName + " " + student.LastName,
                Course = course.Title,
                Grade = enrollment.Grade,
                GraduationDate = student.GraduationDate,
                Status = student.Status.Title
            });
        }
    }