NHibernate挂起延迟加载的查询

NHibernate挂起延迟加载的查询,nhibernate,fluent-nhibernate,lazy-loading,Nhibernate,Fluent Nhibernate,Lazy Loading,首先,我使用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

首先,我使用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坚持这一说法。起初我以为是因为DBA中有那么多记录,大约50万条

但我将筛选结果的行更改为:

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

它工作得很快。但我似乎不明白为什么。有什么想法吗?

在第一种情况下,您将检索所有记录,并使用Linq to对象筛选该列表

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

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

Return CurrentSession.Linq(Of Customer)
…那么问题在于这种转换。只需将第一行更改为:

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

谢谢这非常有效:我认为我的问题是我的返回类型在第一行是IEnumerable,而不是IQueryable。我将来会知道的。