0

I have an Entity Framework class called Student. It has a list of Classes. Now, everytime I (from my view) refer to ViewBag.Student.Classes, it fails with an object disposed exception, because my controller looks like this:

using(var myObjectContext = new ModelContainer()) {
    ViewBag.Student = myObjectContext.UserSet.OfType<Student>().FirstOrDefault(s => s.Id == ActiveStudentSignedIn);
}

Now, I know I could just pass in the student's classes in the viewbag too, but that would increase complexity when using strong-typed partial views that rely on a student and its details.

I think it would be wrong to not having the "using" keyword there, because wouldn't that leave up too much garbage for the garbage collector to collect?

I'm obviously doing something wrong. But what?

Mathias Lykkegaard Lorenzen
  • 15,031
  • 23
  • 100
  • 187

2 Answers2

4

There are two ways to solve this:

  • Use eager loading (Include method in query) and pass all data you need in view from your controller action directly. Currently you receive exception because your view is trying to trigger lazy loading and execute another queries to database but the context is already disposed.
  • Extend lifetime of your context = don't create context per action. Create single context per controller (new instance is created for every request) and dispose context in controller's Dispose method. You can also inject the context into controller from outside - dependency injection but that would require some other infrastructure.
Ladislav Mrnka
  • 360,892
  • 59
  • 660
  • 670
2

You could try eagerly loading associations:

ViewBag.Student = myObjectContext
    .UserSet
    .Include("Classes")
    .OfType<Student>()
    .FirstOrDefault(s => s.Id == ActiveStudentSignedIn);
Darin Dimitrov
  • 1,023,142
  • 271
  • 3,287
  • 2,928