0

I'm getting the following error

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

But I don't understand why the framework is throwing this error. Here is the code.

var bookmark = type.ToLower() == "bookmark"
    ? db.Bookmarks.First(u => u.BookmarkID == id)
    : db.Users.First(u => u.UserID == id).Videos.FirstOrDefault(a => a.Recording)?.Bookmarks.OrderBy(b => b.Timestamp).FirstOrDefault();
if (bookmark != null)
{
    var meta = bookmark.relBookmarkMetadatas.Select(a => new
    {
        Value =
        FormatValue(a.Value, a.MetadataDefinition.MetadataType.ObjectType, a.MetadataDefinition.MetadataType.FormatString),
        a.MetadataDefinition.MetadataClass.Class,
        a.MetadataDefinition.Name,
        a.MetadataDefinition.MetadataType.ObjectType,
        a.MetadataDefinition.MetadataType.FormatString
    });
    return Json(meta, JsonRequestBehavior.AllowGet);
}

Why am I getting this error?

The error is on the

 var meta = bookmark.relBookmarkMetadatas.Select(a => new
devzero
  • 2,510
  • 4
  • 35
  • 55
  • 1
    In which line are you getting the error? – Zalomon Apr 05 '17 at 13:46
  • Enitity framework by default uses lazy-loading..delaying the loading of related data, until you specifically request for it...... maybe try eager loading by using the `.Include()` method... but it would be nice to know which line you are receiving the error on. – Grizzly Apr 05 '17 at 13:54

1 Answers1

1

You're passing a lazily-loaded EntityFramework ICollection to the Json(..) method. At the time that the response is serialized, the EntityFramework context will have been disposed.

Add .ToList() to the end of your ICollection/IQueryable/IEnumerable, before you pass it.

return Json(meta.ToList(), JsonRequestBehavior.AllowGet);
Ben Jenkinson
  • 1,806
  • 1
  • 16
  • 31
  • Thank you so much, for some reason, the WHERE I needed the .ToList() escaped me – devzero Apr 05 '17 at 14:11
  • @devzero No problem :) Generally speaking, as late in the chain as possible, but you do usually need one. It's then fun to learn which things EF can offload to the database, and which things can only be be done in-memory. Also things like `db.People.Where(...).ToList()` is _very_ different to `db.People.ToList().Where(...).ToList()`! – Ben Jenkinson Apr 05 '17 at 14:17