异常的延迟加载(实体框架)(Exception in lazy loading (Entity Fr

2019-07-03 17:54发布

我使用实体框架在我的项目。 问题是众所周知的,但认为解决方案(如: 这和这 )不会为我工作。

/// <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; }
}

怎么了?

Answer 1:

延迟加载工作,直到你DbContext生活。

随着using你处置您DbContext所以当你尝试到外面访问导航属性EF会抛出异常using块。

您可以使用移动测试此Debug.WriteLineusing块,它不会引发异常:

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

并将该溶液是告诉EF到热切加载导航属性与使用Include方法:

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

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


文章来源: Exception in lazy loading (Entity Framework)