Reputation: 11
I am in big need of help.
I am making dynamic query using Criteria:
ICriteria query = session.CreateCriteria(typeof(Employee));
if (searchOptions.FirstName != null)
{
query.Add(Expression.Eq("FirstName", searchOptions.FirstName));
}
if (!searchOptions.LastName != null)
{
query.Add(Expression.Eq("LastName", searchOptions.LastName));
}
if (searchOptions.PhoneNumber != null)
{
query.CreateCriteria("PhoneNumbers")
.Add(Expression.Like("Number", searchOptions.PhoneNumber + "%"));
}
After this I need to have both Total Row Count and Pagination.
For pagination:
query.SetFirstResult(0).SetMaxResults(8);
for rowcount:
query.SetProjection(Projections.RowCountInt64());
How can I execute both in a single query either by using a MultiCriteria or something else.
Please help!
Upvotes: 1
Views: 4105
Reputation: 7803
You can see my answer in nhibernate 2.0 Efficient Data Paging DataList Control and ObjectDataSource .
Code again:
protected IList<T> GetByCriteria(
ICriteria criteria,
int pageIndex,
int pageSize,
out long totalCount)
{
ICriteria recordsCriteria = CriteriaTransformer.Clone(criteria);
// Paging.
recordsCriteria.SetFirstResult(pageIndex * pageSize);
recordsCriteria.SetMaxResults(pageSize);
// Count criteria.
ICriteria countCriteria = CriteriaTransformer.TransformToRowCount(criteria);
// Perform multi criteria to get both results and count in one trip to the database.
IMultiCriteria multiCriteria = Session.CreateMultiCriteria();
multiCriteria.Add(recordsCriteria);
multiCriteria.Add(countCriteria);
IList multiResult = multiCriteria.List();
IList untypedRecords = multiResult[0] as IList;
IList<T> records = new List<T>();
if (untypedRecords != null)
{
foreach (T obj in untypedRecords)
{
records.Add(obj);
}
}
else
{
records = new List<T>();
}
totalCount = Convert.ToInt64(((IList)multiResult[1])[0]);
return records;
}
It clones your original criteria twice: one criteria that return the records for the page and one criteria for total record count. It also uses IMultiCriteria to perform both database calls in one roundtrip.
Upvotes: 5