nhibernate 2.0 Efficient Data Paging DataList Control and ObjectDataSource

拟墨画扇 提交于 2019-12-31 02:09:25

问题


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;
        }

回答1:


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.




回答2:


Got it to work, but two calls

I added itemCount to a ref:



 itemCount = (Int64)_session.CreateQuery("select count(UserId) from User")
                    .UniqueResult();



来源:https://stackoverflow.com/questions/3582611/nhibernate-2-0-efficient-data-paging-datalist-control-and-objectdatasource

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!