Question

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 closed"

Était-ce utile?

La solution

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);
}

Autres conseils

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.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top