我在项目中使用 Entity Framework 。这个问题众所周知,但假设的解决方案(例如this和this)对我不起作用。
/// <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; }
}
怎么了?
答案 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);