Session is Closed - Castle ActiveRecord
What is wrong here?
public IQueryable<Customer> GetAllCustomers()
{
using (SessionScope scope = new SessionScope())
{
return scope.AsQueryable<Customer>();
}
}
var result = from x in GetAllCustomers() select x;
Assert.Greater(result.Count(), 0);
System.ObjectDisposedException : Session is closed! Object name: 'ISession'.
This post didn't help me: Castle ActiveRecord error "Session is close开发者_如何学Cd"
The thing is that the actual query is not being executed in this line:
scope.AsQueryable<Customer>();
Because you only return an IQueryable
object that you can query later.
So, it gets executed when you access the data:
Assert.Greater(result.Count(), 0);
At this point, obviously, the session is already closed (it gets closed when you exit the using
block).
One of the possible solutions would be to move the SessionScope
out of the GetAllCustomers
method:
public IQueryable<Customer> GetAllCustomers(SessionScope scope)
{
return scope.AsQueryable<Customer>();
}
using (SessionScope scope = new SessionScope())
{
var result = from x in GetAllCustomers(scope) select x;
Assert.Greater(result.Count(), 0);
}
The query is actually executed when you run result.Count()
(LINQ queries are lazily executed), but the SessionScope has already been disposed by then.
If it's a web project, use a HTTP-request-scoped SessionScope.
精彩评论