Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I'm having trouble with one of my queries because of EF's change tracking and lazy loading features. The thing is that after I'm getting the result of the query, I'm using AutoMapper to map the domain objects into my business model but it keeps throwing an exception because the context has been disposed.

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

When I look at the resultant collection in the debugger, I see that it is a list of DynamicProxy and not the actual entity. I tried to stop Change Tracking but that did not help. Here's my code:

    public List<ContentTypeColumn> GetContentTypeColumns(Int64 contentTypeId)
    {
        List<ContentTypeColumn> result = new List<ContentTypeColumn>();
        using (SCGREDbContext context = new SCGREDbContext())
        {                
            ContentType contentType = context.ContentTypes.Include("Parent").AsNoTracking().FirstOrDefault(x => x.Id.Equals(contentTypeId));

            result.AddRange(contentType.ContentTypeColumns.ToList());
            while (contentType.Parent != null)
            {
                result.AddRange(contentType.Parent.ContentTypeColumns.ToList());
                contentType = contentType.Parent;
            }    
        }
        return result.ToList();
    }

Note: If you need to look into my domain model involved in this operation you can refer to this question.

like image 703
Kassem Avatar asked Oct 04 '12 16:10

Kassem


1 Answers

If you need to stop lazy loading and dynamic change tracking you can simply turn it off:

using (SCGREDbContext context = new SCGREDbContext())
{   
    context.Configuration.ProxyCreationEnabled = false;
    ...
}
like image 187
Ladislav Mrnka Avatar answered Oct 26 '22 18:10

Ladislav Mrnka