0

我正在使用 ASP.NET MVC4 EF CodeFirst。

需要帮助在索引操作中编写 LINQ(到实体)代码以获取所选学生参加的课程的集合。连接表与有效负载的关系是多对多的。

//StudentController
//-----------------------

public ActionResult Index(int? id)
{
    var viewModel = new StudentIndexViewModel();
    viewModel.Students = db.Students;

    if (id != null)
    {
        ViewBag.StudentId = id.Value;
        // *************PROBLEM IN LINE DOWN. HOW TO MAKE COURSES COLLECTION? 
        viewModel.Courses = db.Courses
            .Include(i => i.StudentsToCourses.Where(t => t.ObjStudent.FkStudentId == id.Value));
    }


    return View(viewModel);
}

我得到的错误是:

The Include path expression must refer to a navigation property defined on the type. Use dotted paths for reference navigation properties and the Select operator for collection navigation properties.

我有模型(第三个是用于连接有效负载的表):

//MODEL CLASSES
//-------------

public class Student
{
    public int StudentId { get; set; }
    public string Name { get; set; }

    public virtual ICollection<StudentToCourse> StudentsToCourses { get; set; }
}

public class Course
{
    public int CourseId { get; set; }
    public string Title { get; set; }

    public virtual ICollection<StudentToCourse> StudentsToCourses { get; set; }
}

public class StudentToCourse
{
    public int StudentToCourseId { get; set; }
    public int FkStudentId { get; set; }
    public int FkCourseId { get; set; }
    public string Classroom { get; set; }

    public virtual Student ObjStudent { get; set; }
    public virtual Course ObjCourse { get; set; }
}

然后,这是我需要传递给视图的模型视图

//VIEWMODEL CLASS
//---------------

public class StudentIndexViewModel
{
    public IEnumerable<Student> Students { get; set; }
    public IEnumerable<Course> Courses { get; set; }
    public IEnumerable<StudentToCourse> StudentsToCourses { get; set; }
}
4

1 回答 1

1

EF 不支持条件包含。您需要包含全部或全部内容(即没有Where在里面Include

如果您只需要获取某些关系的数据,则可以将其选择为匿名类型,例如(显然未经测试);

var intermediary = (from course in db.Courses
                    from stc in course.StudentsToCourses
                    where stc.ObjStudent.FkStudentId == id.Value
                    select new {item, stc}).AsEnumerable();

显然,这将需要一些代码更改,因为它不再是带有 StudentsToCourses 集合的直接课程。

于 2013-02-02T11:41:22.977 回答