MVC4教程 - 渴望加载一个外键对象的属性,它本身已被急切加载

时间:2013-11-08 13:55:35

标签: c# asp.net asp.net-mvc entity-framework asp.net-mvc-4

我正在使用MVC4和EF5,我一直在这个页面上完成Contoso大学的教程: http://www.asp.net/mvc/tutorials/getting-started-with-ef-5-using-mvc-4/implementing-basic-crud-functionality-with-the-entity-framework-in-asp-net-mvc-application

The Entity Framework模型类的相关部分:

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的外键)为null。 换句话说,对于每个学生,将加载注册集合,但这些注册尚未加载其课程属性。 我无法弄清楚如何使用Eager Loading来加载每个Enrollment的Course属性。 如何在视图中显示课程标题?

我发现硬编码的“Include”字符串可以工作(在Controller中):

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();

1 个答案:

答案 0 :(得分:2)

请勿在c#文件中忘记这一点:

using System.Data.Entity;

编辑:

或者只是将您的课程属性标记为延迟加载的虚拟

public class Enrollment
{

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