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

I am developing a WCF data service. when I try to access it from the client side, I get this exception:

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

the 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;
}
+5
source share
4 answers

I suspect the problem is with code ...that you are not showing.

Before you return it, be sure to fully evaluate your request. For example, instead of just doing:

return studentQry;

Try to do:

return studentQry.ToList();

Edit:

, , , IQueryable<T> IEnumerable<T>, . IQueryable<T> , , "" .

WCF , . IEnumerable<T> , IQueryable<T>. , , .

+15

- . , . IQueryable , , . , sevice IDisposable IDisposable. Dispose()

+6

, , , student.classes - , .

+2
source

It is your use that causes it. The DataContext is deleted before the linq request is received. You can return studentQry.ToList () and see if this works. If it is not, try

List<Student> retValue;
retValue = studentQry.ToList();
return retValue;

Finally, it is ugly, but if you do not use it, you will not have this problem. Ultimately, it must be disposed of and cleaned by garbage collection.

+2
source

All Articles