2

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

Exception (***):

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

What's wrong?

Community
  • 1
  • 1
patryk.beza
  • 4,125
  • 5
  • 34
  • 49

1 Answers1

4

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);
BenMorel
  • 30,280
  • 40
  • 163
  • 285
nemesv
  • 133,215
  • 15
  • 395
  • 348
  • 1
    @patryk.beza you can have multiple includes: `dbb.Lecturers.Include(l => l.AcademicDegree).Include(l => l.Timetables).Include(l => l.Courses )` I know it is not so nice but this is how EF works. – nemesv Nov 10 '12 at 14:31