J86
J86

Reputation: 15307

"The ObjectContext instance has been disposed" - even with a using(context) statement and ToList()

I have an MVC3 Project running with EF Code First.

Here is my code for Home/Index:

public ActionResult Index()
{
    var IndVM = new IndexVM();
    using (QuoteContext QDomain = new QuoteContext())
    {
        IndVM.Quotes = QDomain.Quotes.Include("Tags").Include("Author").OrderByDescending(x => x.CreatedOn).Take(5).ToList();
        IndVM.Tags = QDomain.Tags.OrderByDescending(x => x.Quotes.Count).ToList();
        IndVM.Authors = QDomain.Authors.OrderByDescending(x => x.Quotes.Count).Take(5).ToList();
    }
    return View(IndVM);
}

As you can see I have the Querying stuff inside a using statement, and I am also calling the ToList(), but I still get the error:

The ObjectContext instance has been disposed and can no longer be used for operations that require a connection.

Is this a bug in EF Code First?

Upvotes: 2

Views: 823

Answers (1)

Merlyn Morgan-Graham
Merlyn Morgan-Graham

Reputation: 59151

You have to turn off lazy loading, otherwise the serializer will try to traverse navigation properties and throw this exception.

public ActionResult Index()
{
    var IndVM = new IndexVM();
    using (QuoteContext QDomain = new QuoteContext())
    {
        QDomain.ContextOptions.LazyLoadingEnabled = false;
        // Query and populate IndVM here...
    }
    return View(IndVM);
}

Upvotes: 1

Related Questions