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

1

6

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.

Macdermot answered 4/10, 2012 at 16:57 Comment(3)
Lazy loading? That would cause this.Manion
I know, and I'm trying to avoid Lazy Loading in this particular case, but I cannot find a way around it. Any suggestions?Macdermot
Possible duplicate of How to solve the error The ObjectContext instance has been disposed and can no longer be used for operations that require a connectionPlethoric
H
20

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;
    ...
}
Hospitaler answered 4/10, 2012 at 17:50 Comment(1)
Perfect! This just saved me so much time!Ritornello

© 2022 - 2024 — McMap. All rights reserved.