Exception in lazy loading (Entity Framework)

对着背影说爱祢 提交于 2019-12-02 01:13:23
nemesv

Lazy loading works until your DbContext lives.

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.

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

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);
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!