我在我的项目中使用 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;
}
异常(***):
The ObjectContext instance has been disposed and can no longer be used for operations that require a connection.
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; }
}
出了什么问题?
最佳答案
延迟加载将一直有效,直到您的 DbContext
存活为止。
通过 using
,您可以处置 DbContext
,因此当您尝试访问 using
block 外部的导航属性时,EF 将引发异常。
您可以通过将 Debug.WriteLine
移动到 using
block 内来测试这一点,这样它就不会抛出异常:
using (var dbb = new AcademicTimetableDbContext())
{
query = (from b in dbb.Lecturers select b).ToList();
Debug.WriteLine(query[0].AcademicDegree);
}
解决方案是告诉 EF eagerly load the navigation properties使用 using Inlude
方法:
using (var dbb = new AcademicTimetableDbContext())
{
query = (from b in dbb.Lecturers.Include(l => l.AcademicDegree) select b)
.ToList();
}
Debug.WriteLine(query[0].AcademicDegree);
关于entity-framework - 延迟加载异常( Entity Framework ),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13322661/