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;
}
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.
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()
Its probably that the client is trying to access a sub property, eg if student.classes is another entity and you try to access it on client. Need to specify include on any sub entities
It is your using that is causing it. The DataContext is being disposed before the linq query evaluates. You can return studentQry.ToList() and see if that works. If that doesn't, try
List<Student> retValue;
retValue = studentQry.ToList();
return retValue;
Finally, it is ugly, but if you don't use a using, you will not have this issue. It should get disposed and cleaned up by garbage collection eventually.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With