2011-02-24 100 views
0

这里有什么问题?会话已关闭 - Castle ActiveRecord

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: 会话关闭!对象名称: 'ISession'。

这个帖子并没有帮助我: Castle ActiveRecord error "Session is closed"

回答

3

的事情是,实际的查询不被这一行执行:

scope.AsQueryable<Customer>(); 

因为你只返回一个IQueryable对象,以后可以查询。

Assert.Greater(result.Count(), 0); 

在这一点上,显然,会话已关闭(它会在你退出using块关闭):

所以,当你访问该数据被执行。

一个可能的解决方案是将SessionScope搬出GetAllCustomers方法:

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

感谢帕夫洛。你知道是否有可能检测到查询不再被使用吗? – Eduardo 2011-02-24 16:48:47

3

当您运行result.Count()(LINQ查询懒洋洋地执行)实际执行的查询,但SessionScope已被释放到那时。

如果这是一个web项目,请使用HTTP-request-scoped SessionScope