Question

My object eventTypeList goes out of context, even if its in the using. Any advice?

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

public ActionResult GetEventTypeList()
{
    List<EventType> eventTypeList;
    using (var db = new ICTTBEntities())
    {
        eventTypeList = (from et in db.EventTypes select et).ToList();
        var result = new { Result = "OK", Records = eventTypeList };

        return Json(result, JsonRequestBehavior.AllowGet);
    }
}
Was it helpful?

Solution

The problem is likely one or more relations that are being lazily loaded rather than eagerly loaded. The good news is that you don't need the using statement for a DbContext as the context already manages the connections, leaving little need for the Dispose (cf, http://stephenwalther.com/archive/2008/08/20/asp-net-mvc-tip-34-dispose-of-your-datacontext-or-don-t.aspx). Alternatively, you can make sure that any relations that you have are eagerly loaded by setting the load options for the context.

Note: if you use IoC and inject the context rather than create it directly, you can avoid the problem entirely as the DI framework will take care of cleaning up the context for you.

OTHER TIPS

Set the lazy Load to disable :

[...]
using (var db = new ICTTBEntities())
    {
         db.Configuration.LazyLoadingEnabled = false;
         [...]
    }

see more informations at http://msdn.microsoft.com/en-us/library/bb896272.aspx

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top