Nhibernate - Paging and eager loading entities
-
30-09-2019 - |
Question
I have two entities, a team and an employee.
I want get a list of employees with eager loaded teams. The list has to be paged.
public PagedList<Employee> GetAllEmployeesWithEagerLoadedTeams(int page, int pageSize)
{
var criteria = GetSession()
.CreateCriteria(typeof (Employee))
.SetFetchMode(DomainModelHelper.GetAssociationEntityNameAsPlural(typeof (Team)),FetchMode.Eager);
var totalCount = criteria
.SetProjection(Projections.RowCount())
.FutureValue<Int32>().Value;
return criteria
.SetFirstResult(page * pageSize)
.SetMaxResults(pageSize)
.Future<Employee>()
.ToPagedList(page, pageSize, totalCount);
}
Why this does not work?
SQL results:
SELECT count(*) as y0_ FROM [Employee] this_;
SELECT TOP 10 y0_ FROM (SELECT count(*) as y0_,
ROW_NUMBER() OVER(ORDER BY CURRENT_TIMESTAMP) as __hibernate_sort_row FROM [Employee] this_) as query WHERE query.__hibernate_sort_row > 10 ORDER BY query.__hibernate_sort_row;
Solution
You are trying to reuse the criteria variable which already has the count projection and future value specified. You need to create a new criteria for your second query.
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow