会话已关闭 - Castle ActiveRecord

发布于 2024-10-18 17:49:45 字数 556 浏览 0 评论 0原文

这里有什么问题吗?

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

迷荒 2024-10-25 17:49:45

问题是,实际的查询并未在这一行中执行:

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

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);
}
庆幸我还是我 2024-10-25 17:49:45

当您运行 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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文