延迟加载中的异常(实体框架)

时间:2012-11-10 13:57:24

标签: entity-framework exception orm lazy-loading dispose

我在项目中使用 Entity Framework 。这个问题众所周知,但假设的解决方案(例如thisthis)对我不起作用。

/// <summary>
/// Returns complete list of lecturers from DB.
/// </summary>
public IEnumerable<Lecturer> GetAllLecturers()
{
    IList<Lecturer> query;
    using (var dbb = new AcademicTimetableDbContext())
    {
        query = (from b in dbb.Lecturers select b).ToList();
    }
    Debug.WriteLine(query[0].AcademicDegree); // Exception (***)
    return query;
}

例外(***):

  

ObjectContext实例已被释放,不能再用于需要连接的操作。

public class Lecturer
{
    public Lecturer()
    {
        this.Timetables = new List<Timetable>();
        this.Courses = new List<Course>();
    }

    public int Id_Lecturer { get; set; }
    public string Name { get; set; }
    public string Surname { get; set; }
    public string Phone_Number { get; set; }
    public Nullable<int> Academic_Degree_Id { get; set; }
    public virtual AcademicDegree AcademicDegree { get; set; }
    public virtual ICollection<Timetable> Timetables { get; set; }
    public virtual ICollection<Course> Courses { get; set; }
}

怎么了?

1 个答案:

答案 0 :(得分:4)

延迟加载有效,直到DbContext生命。

使用using释放DbContext,以便当您尝试访问using块之外的导航属性时,EF会抛出异常。

您可以通过移动Debug.WriteLine块内的using来测试它,它不会引发异常:

using (var dbb = new AcademicTimetableDbContext())
{
    query = (from b in dbb.Lecturers select b).ToList();
    Debug.WriteLine(query[0].AcademicDegree);
}

解决方法是使用Include方法告诉EF eagerly load the navigation properties

using (var dbb = new AcademicTimetableDbContext())
{
    query = (from b in dbb.Lecturers.Include(l => l.AcademicDegree) select b)
      .ToList();

}
Debug.WriteLine(query[0].AcademicDegree);