The ObjectContext object has been deleted and cannot be utilized for any activities that require a connection.

c# entity-framework exception-handling wcf wcf-data-services


A WCF Data Service is what I'm creating. I encounter the following error while trying to access it from the client side:

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


public IQueryable<Student> GetUsersByClassId(string classId)
    Check.Argument.IsNotEmptyOrNull(classId, "classId");

    using (var db = new schoolContext(connectionString))
        ((IObjectContextAdapter)db).ObjectContext.ContextOptions.ProxyCreationEnabled =  false;
        ((IObjectContextAdapter)db).ObjectContext.ContextOptions.LazyLoadingEnabled = false;

        var studentQry = from s in db.Student.Include("Class")
                         where s.Class.Id == classId
                         select s;

        if(studentQry == null) 
            return new List<Student>().AsQueryable();
           return studentQry;
5/18/2012 6:46:30 PM

Accepted Answer

I believe the code highlighted contains the issue.... which you don't display.

Before returning your question, be sure to properly review it. Instead than just performing:

return studentQry;

Try this:

return studentQry.ToList();


Now that you've revised your inquiry to indicate that you're coming backIQueryable<T> in place ofIEnumerable<T> there is a different problem. by going backIQueryable<T> You imply that the type may be "queried" directly on the server side in your way.

However, WCF must use a specific implementation type since it is serializing information over the wire.IEnumerable<T> is acceptable but notIQueryable<T> . Change this to a type that will evaluate entirely so that the results may be accurately provided.

3/29/2011 5:54:04 PM

Popular Answer

The Using statement is to blame for this. Your function disposes of the object context when it has finished running. You receive the Exception because a disposed object is attempted to be used when the result IQueryable is enumerated. Take using out of the equation and let your service implement IDisposable, where it will dispose of your object context. Dispose()

Related Questions


Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow