【问题标题】:NHibernate Hanging on Lazy Loaded QueryNHibernate 挂在延迟加载的查询上
【发布时间】:2009-12-14 20:57:40
【问题描述】:

首先,我将 Fluent NHibernate 与 LinqToNHibernate 一起使用。

我有一个查询,可以根据用户输入的数据对表进行搜索。所以,例如,我正在做这样的事情:

        'build the initial query that we will filter--this is lazy loaded
    Dim results As IEnumerable(Of Customers) = Me.GetCustomers()

    'filter by owner name
    If String.IsNullOrEmpty(OwnerName) = False Then
        results = results.Where(Function(s) s.Name.Contains(OwnerName))            
    End If

    'execute query
    results = results.ToList()

因此,如果用户想按名称搜索,基本上我会在 sql 语句上构建 where 语句。我在我的映射中使用了所有惰性配置,因此在调用“ToList()”之前,查询不应该检索项目。问题是 NHibernate 挂在这个声明上。一开始我以为是因为db里的记录太多了(大约50万条)。

但我将过滤结果的那一行更改为:

results = SessionFactoryProvider.SessionFactory.CurrentSession.Linq(Of Customer).Where(Function(c) c.Name.Contains(OwnerName))

而且它的工作速度非常快。但我似乎无法弄清楚为什么。有什么想法吗?

【问题讨论】:

    标签: nhibernate fluent-nhibernate lazy-loading


    【解决方案1】:

    在第一种情况下,您正在检索所有记录并使用 Linq-to-objects 过滤该列表。

    在第二种情况下,您将查询发送到数据库(NHibernate.Linq 将您的表达式转换为 SQL WHERE 子句)。

    现在,我不知道 GetCustomers 的返回类型是什么,但由于您将其存储到 IEnumerable(Of Customer) 中,.NET 无法了解底层提供程序。如果 GetCustomers 的代码类似于:

    Return CurrentSession.Linq(Of Customer)
    

    ...那么问题出在转换上。只需将第一行更改为:

    Dim results As IQueryable(Of Customers) = Me.GetCustomers()
    

    【讨论】:

    • 谢谢;这工作得很好:) 我认为我的问题是我的返回类型在第一行是 IEnumerable 而不是 IQueryable。我以后会知道的。
    猜你喜欢
    • 2011-07-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-11-04
    • 2013-12-10
    • 2011-10-17
    • 1970-01-01
    相关资源
    最近更新 更多