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


I am developing a WCF Data Service. when I try accessing it from the client side, I get this exception :

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 suspect the problem is in the code marked ..., which you're not showing.

Make sure to fully evaluate your query before returning it. For example, instead of just doing:

return studentQry;

Try doing:

return studentQry.ToList();


Now that you've changed your question to reflect that you're returning IQueryable<T> instead of IEnumerable<T>, there is a separate issue. By returning IQueryable<T> from your method, you're suggesting that the type can be "queried" directly on the server side.

However, WCF is serializing this across the wire, and needs to use a concrete implementation type. IEnumerable<T> is allowed, but not IQueryable<T>. You should switch this to a type that will evaluate fully so the results can be passed correctly.

3/29/2011 5:54:04 PM

Popular Answer

This is because of Using statement. When your function finishes execution, it disposes object context. When the result IQueryable is enumerated, it tries to use disposed object, so you get the Exception. Remove using, let your sevice implement IDisposable and dispose your object context in IDisposable.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