本文介绍了延迟加载中的异常(实体框架)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在项目中使用实体框架.这个问题是众所周知的,但应该可以解决(例如,和)对我不起作用.

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

这篇关于延迟加载中的异常(实体框架)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-28 04:30