gpt4 book ai didi

nhibernate - NHibernate:获取任意条件查询返回的行数的通用方法

转载 作者:行者123 更新时间:2023-12-04 00:14:01 25 4
gpt4 key购买 nike

我知道CriteriaTransformer.TransformToRowCount,但是根据link和我的经验,它不适用于聚合函数(它们经常使用)。由于我正在为我的应用程序编写一种分页框架,因此为每个数据查询编写“计数”查询将非常繁琐。
有什么想法可以对此进行优化吗?

最佳答案

这并不难:

private IPagedList<ProjT> FindPaged<ProjT>(DetachedCriteria criteria, int pageIndex, int pageSize, IResultTransformer resultTransformer)
{
int firstResult = pageIndex == 1 ? 0 : (pageIndex - 1) * pageSize;

var countCriteria = CriteriaTransformer
.Clone(criteria)
.SetProjection(Projections.RowCount());

countCriteria.ClearOrders();

IMultiCriteria multiCriteria = Session.CreateMultiCriteria();
multiCriteria.Add(countCriteria);

criteria.SetFirstResult(firstResult).SetMaxResults(pageSize);

if (resultTransformer != null)
{
criteria.SetResultTransformer(resultTransformer);
}

multiCriteria.Add(criteria);

var result = multiCriteria
.List()
.Cast<System.Collections.ArrayList>()
.ToList();

PagedList<ProjT> list = new PagedList<ProjT>(
result[1].Cast<ProjT>().ToList<ProjT>(),
pageIndex,
pageSize,
(int)result[0][0]);

return list;
}


其中IPagedList是:

public interface IPagedList<T> : ICollection<T>
{
int TotalPages { get; }
int TotalCount { get; }
int PageIndex { get; }
int PageSize { get; }
bool HasPreviousPage { get; }
bool HasNextPage { get; }
bool IsFirstPage { get; }
bool IsLastPage { get; }
}


和实现:

public class PagedList<T> : List<T>, IPagedList<T>
{
public PagedList(IEnumerable<T> source, int pageIndex, int pageSize) :
this(source, pageIndex, pageSize, source.Count())
{ }

public PagedList(IEnumerable<T> source, int pageIndex, int pageSize, int totalCount)
{
this.TotalCount = totalCount;
this.PageSize = pageSize;
this.PageIndex = pageIndex;

double pc = this.TotalCount / this.PageSize;
if (this.TotalCount % this.PageSize > 0)
{
pc++;
}
this.TotalPages = (int)pc;

this.HasPreviousPage = (PageIndex > 1);
this.HasNextPage = (PageIndex * PageSize) < TotalCount;
this.IsFirstPage = (this.PageIndex == 1);
this.IsLastPage = (this.PageIndex == this.TotalPages);

this.AddRange(source);
}

public int TotalPages { get; private set; }
public int TotalCount { get; private set; }
public int PageIndex { get; private set; }
public int PageSize { get; private set; }
public bool HasPreviousPage { get; private set; }
public bool HasNextPage { get; private set; }
public bool IsFirstPage { get; private set; }
public bool IsLastPage { get; private set; }
}

关于nhibernate - NHibernate:获取任意条件查询返回的行数的通用方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3877024/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com