entity-framework - 延迟加载异常( Entity Framework )

标签 entity-framework exception orm lazy-loading dispose

我在我的项目中使用 Entity Framework 。这个问题是众所周知的,但假设的解决方案(例如 thisthis )对我来说不起作用。

/// <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/

相关文章:

c# - 使用 "using"语法时出现流关闭错误

django - 如何通过 Django 中的 prefetch_related 过滤具有更多条件的反向外键

entity-framework - 使用 F# 配置 EF Core

c# - Entity Framework 迁移: Sequence contains more than one matching element

c# - MigrateDatabaseToLatestVersion 没有运行 Seed() 方法

python - 在 SQLAlchemy 的 HAVING() 子句中使用标签

java - 如何关闭 hbm2ddl?

c# - LINQ - 如何查询仅具有开始日期的有效日期范围

c# - 当我通过安装程序运行应用程序时,出现错误 "Bad method token. "

java - Java 7 中多异常捕获的使用