0

我正在使用 MVC4 和 EF5,并且一直在学习此页面上的 Contoso 大学教程: http ://www.asp.net/mvc/tutorials/getting-started-with-ef-5-using-mvc- 4/实现-基本-crud-功能-with-the-entity-framework-in-asp-net-mvc-application

实体框架模型类的相关部分:

public class Student
{
    public int StudentID { get; set; }
    public string LastName { get; set; }
    public virtual ICollection<Enrollment> Enrollments { get; set; }
}

public enum Grade { A,B,C,D,F}
public class Enrollment
{
    public int EnrollmentID { get; set; }
    public int CourseID { get; set; }
    public int StudentID { get; set; }
    public Grade? Grade { get; set; }
    public Course Course { get; set; }
    public Student Student { get; set; }
}

public class Course
{
    public int CourseID { get; set; }
    public string Title { get; set; }
    public virtual ICollection<Enrollment> Enrollments { get; set; }
}

在控制器中:

public ActionResult Details(int id = 0) {
    Student student = db.Students.Find(id);
    return View(student);
}

视图的相关位:

@foreach (var item in Model.Enrollments) {
    <tr>
    <td>
        @Html.DisplayFor(modelItem => item.Course.Title) //this does not display as Course is null
    </td>
    <td>
        @Html.DisplayFor(modelItem => item.Grade)
    </td>
    </tr>
}

与教程所说的相反,对我来说,视图不显示课程标题,它只显示成绩。

Course Title    Grade
                A
                C
                B

调试显示 Course 属性(表示 Course 的外键)为空。换句话说,对于每个学生,已加载 Enrollments 集合,但这些注册尚未加载其 Course 属性。我无法弄清楚如何使用 Eager Loading 来加载每个 Enrollment 的 Course 属性。如何让课程标题显示在视图中?

我发现硬编码的“包含”字符串有效(在控制器中):

Student student = db.Students.Where(x => x.StudentID == id).Include("Enrollments.Course").Single();

但我无法弄清楚如何使用 lambda 函数或任何其他函数来做到这一点。

我尝试了以下但没有成功:

Student student = db.Students.Where(x => x.StudentID == id).Include(y => y.Enrollments.Course).Single();
Student student = db.Students.Where(x => x.StudentID == id).Include(y => y.Enrollments).Include(z => z.Enrollments.Course).Single();
4

1 回答 1

2

不要在你的 c# 文件中忘记这一点:

using System.Data.Entity;

编辑:

或者只是将您的 Course 属性标记为虚拟以进行延迟加载

public class Enrollment
{

        public virtual Course Course { get; set; }
        public virtual Student Student { get; set; }
}
于 2013-11-08T14:19:15.377 回答