How would I do what Scott has done in one call using nHibernate 2 ObjectDataSource
http://weblogs.asp.net/scottgu/archive/2006/01/07/434787.aspx
below is my Data access method
public IList GetListOfUser(int rows, int pageIndex) {
IList userList = null;
using (ITransaction tx = _session.BeginTransaction()) {
try {
userList = _session.CreateQuery("Select u from User u where u.DateSubmitted is not null")
.SetFirstResult(rows * (pageIndex - 1) + 1)
.SetMaxResults(rows)
.List();
tx.Commit();
} catch (NHibernate.HibernateException ex) {
tx.Rollback();
AppUtil.LogHelper.WriteLog(LogLevel.ERROR, ex.ToString());
throw;
}
}
return userList;
}
Actually, you can get the result page AND total records count in one roundtrip to the server using this helper method if you are using ICriteria queries:
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 clone 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.
Got it to work, but two calls
I added itemCount to a ref:
itemCount = (Int64)_session.CreateQuery("select count(UserId) from User")
.UniqueResult();