Search code examples
.netdatabasenhibernateexceptioncastle-activerecord

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


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