nhibernate 2.0高效数据分页DataList控件和ObjectDataSource

时间:2010-08-27 08:50:46

标签: c# asp.net nhibernate objectdatasource

我如何使用 nHibernate 2 ObjectDataSource

在一次通话中完成Scott的操作

http://weblogs.asp.net/scottgu/archive/2006/01/07/434787.aspx

下面是我的数据访问方法



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

2 个答案:

答案 0 :(得分:3)

实际上,如果您正在使用ICriteria查询,则可以使用此帮助程序方法将结果页面和总记录数一次性地计入服务器:

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

它将原始标准克隆两次:一个标准返回页面记录,一个条件记录总记录数。它还使用IMultiCriteria在一次往返中执行两个数据库调用。

答案 1 :(得分:0)

让它工作,但两个电话

我将itemCount添加到ref:



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