问题描述
我在项目中使用实体框架.这个问题是众所周知的,但应该可以解决(例如,此和)对我不起作用.
I use Entity Framework in my project. The issue is well known but supposed solutions (eg. this and this) doesn't work for me.
/// <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;
}
异常(***):
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
生效,延迟加载才起作用.
Lazy loading works until your DbContext
lives.
使用using
处置DbContext
,以便当您尝试访问using
块之外的导航属性时,EF将引发异常.
With the using
you dispose your DbContext
so EF will throw an exception when you try to access the navigation properties outside the using
block.
您可以通过将Debug.WriteLine
移到不会引发异常的using
块内来进行测试:
You can test this with moving the Debug.WriteLine
inside the using
block where it won't throw exception:
using (var dbb = new AcademicTimetableDbContext())
{
query = (from b in dbb.Lecturers select b).ToList();
Debug.WriteLine(query[0].AcademicDegree);
}
解决方案是告诉EF使用以下方法迅速加载导航属性使用Include
方法:
And the solution is to tell EF to eagerly load the navigation properties with the using Include
method:
using (var dbb = new AcademicTimetableDbContext())
{
query = (from b in dbb.Lecturers.Include(l => l.AcademicDegree) select b)
.ToList();
}
Debug.WriteLine(query[0].AcademicDegree);
这篇关于延迟加载中的异常(实体框架)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!