会话已关闭 - 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.ObjectDisposeException: 会议已结束!对象名称: 'ISession'。
这篇文章对我没有帮助: 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"
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
问题是,实际的查询并未在这一行中执行:
因为您只返回一个可以稍后查询的 IQueryable 对象。
因此,当您访问数据时,它就会被执行:
此时,显然会话已经关闭(当您退出
using
块时,会话就会关闭)。可能的解决方案之一是将
SessionScope
移出GetAllCustomers
方法:The thing is that the actual query is not being executed in this line:
Because you only return an
IQueryable
object that you can query later.So, it gets executed when you access the data:
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 theGetAllCustomers
method:当您运行
result.Count()
时,查询实际上被执行(LINQ 查询是延迟执行的),但此时 SessionScope 已经被释放。如果是 Web 项目,请使用 HTTP-request-scoped SessionScope。
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.