gpt4 book ai didi

linq - NHibernate Linq 提供者和 take() skip() 与急切获取

转载 作者:行者123 更新时间:2023-12-03 12:30:57 25 4
gpt4 key购买 nike

我在 NHibernate 3.2 和 SQLite 提供程序中有这个简单的 linq 查询:

var all = (from book in Session.Query<Book>() select book)
.Skip(15)
.Take(15)
.ToList();

此查询正确返回 15 个实体,但是当我尝试像这样使用 FetchMany 急切加载依赖集合时:
var all = (from book in Session.Query<Book>() select book)
.FetchMany(books => books.Authors)
.Skip(15)
.Take(15)
.ToList();

我只返回了 11 个实体。这是错误还是我缺少的东西?

这是生成的 SQL 查询
select
book0_.Id as Id2_0_,
author2_.Id as Id0_1_,
book0_.Title as Title2_0_,
book0_.Sort as Sort2_0_,
book0_.TimeStamp as TimeStamp2_0_,
book0_.PubDate as PubDate2_0_,
book0_.Series_Index as Series6_2_0_,
book0_.Author_Sort as Author7_2_0_,
book0_.Isbn as Isbn2_0_,
book0_.Lccn as Lccn2_0_,
book0_.Path as Path2_0_,
book0_.Flags as Flags2_0_,
book0_.Uuid as Uuid2_0_,
book0_.Has_Cover as Has13_2_0_,
book0_.Last_Modified as Last14_2_0_,
author2_.Name as Name0_1_,
author2_.Sort as Sort0_1_,
author2_.Link as Link0_1_,
authors1_.book as book0__,
authors1_.author as author0__
from
books book0_
left outer join
books_authors_link authors1_ on book0_.Id=authors1_.book left outer join authors author2_
on authors1_.author=author2_.Id
order by book0_.Id asc
limit 15 /* @p0 */ offset 0 /* @p1 */

这有效地将结果集限制为 15 行,而不是我想要的 15 个实体。

最佳答案

skip 和 take 被转换为 sql 中的等价物,它限制了行,并且由于您急切地使用连接进行提取,因此您无能为力。

要急切地获取前 15 本书,您需要:

var all = Session.Query<Book>()
.Skip(15)
.Take(15)
.ToList();

var ids = all.Select(b => b.Id).ToList();

// fetch all Authors of the books, now the books in all have initialized Authors
Session.Query<Book>()
.Where(b => ids.Contains(b.Id))
.FetchMany(books => books.Authors)
.List();

虽然这有 2 次往返

更新:用QueryOver 来回一次,也许你可以翻译成Linq
var subquery = QueryOver.Of<Book>()
.Skip(15)
.Take(15)
.Select(b => b.Id);

var all = Session.QueryOver<Book>()
.WithSubquery.WhereProperty(b => b.Id).In(subquery)
.Fetch(books => books.Authors).Eager
.ToList();

关于linq - NHibernate Linq 提供者和 take() skip() 与急切获取,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9729262/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com