MVC 5 Linq-SQL从3个连接表中执行搜索

时间:2014-01-15 07:29:47

标签: c# asp.net-mvc linq

MVC MODEL
使用此模型,我想将课程表的左外连接执行到学生表,并在课程中使用搜索下拉菜单显示它们。 我的MVC代码是:

  var query = from c in db.Students
                    join o in db.Enrollments on c.StudentID equals o.StudentID 
                    join co in db.Courses on o.CourseID equals co.CourseID into sr
                    from x in sr.DefaultIfEmpty()
                    select new Student
                    {
                         FirstName=c.FirstName,
                         LastName=c.LastName,
                         EnrollmentDate=c.EnrollmentDate,
                         MiddleName=c.MiddleName,
                         StudentID=c.StudentID
                        //StudentName = c.FirstName.ToString(),
                        //CourseID = x.CourseID.ToString(),
                        //CourseName = x.Title.ToString()
                        //== null ? -1 : x.Title
                    };   
 if (!string.IsNullOrEmpty(course))
        {
         students = query.Where(x => x.CourseName == course).Select(item=>new Student(){FirstName = c.FirstName.ToString()}).ToList();
        }
        return View(students);

但我无法让它发挥作用。有人可以请教我如何正确地做到这一点。 这是示例屏幕: enter image description here

1 个答案:

答案 0 :(得分:1)

    public List<Student> GetStudentsByCourseName(string courseName)
    {
        var list = new List<Student>();
        var course = db.Courses.SingleOrDefault(o => o.Title == courseName);

        if (course != null)
        {
            list = course.Enrollments.Select(o => new Student {
                    FirstName = o.Student.FirstName,
                    LastName = o.Student.LastName
                }).ToList();
        }

        return list;
    }