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

centity-frameworkexception handlingwcfwcf-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.

Code:

[WebGet]
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();
        else 
           return studentQry;
}

Best 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();

Edit:

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.

Related Topic