我在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个实体。
答案 0 :(得分:13)
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();
答案 1 :(得分:0)
var data = session.QueryOver<EmployeeDetails>()
.Where(x => x.Salary > 2000)
//.Take(2)
.Skip(2)
.Take(2)
.List();
//if take is before skip then it will skip the last (mentioned digits) rows
//if take is after skip then it will skip the first (mentioned digits) rows