EF如何分页最大优化

编程

publicstaticclass QueryableExtension

{

publicstatic IQueryable<T> Paged<T>(this IQueryable<T> query, Expression<Func<T, object>> expression, OrderByType orderByType = OrderByType.Desc,int currentPage = 1, int pageSize = 5,int pageCount = 0)

{

if (currentPage < 1)

{

currentPage = 1;

}

var Skip = (currentPage - 1) * pageSize;

var Take = pageSize;

OrderByType byType = orderByType;

var MaxPageIndex = pageCount % pageSize == 0 ? pageCount / pageSize : pageCount / pageSize + 1;

if (currentPage > MaxPageIndex / 2)//页码大于一半用倒序

{

var Mod = pageCount % pageSize;

var Page = (int)Math.Ceiling((Decimal)pageCount / pageSize);

if (currentPage * pageSize >= pageCount)

{

Skip = 0; Take = Mod == 0 ? pageSize : Mod;

}

else

{

Skip = (Page - currentPage - 1) * pageSize + Mod;

}

byType = orderByType == OrderByType.Desc ? OrderByType.Asc : OrderByType.Desc;

}

else

{

byType = orderByType == OrderByType.Desc ? OrderByType.Desc : OrderByType.Asc;

}

if (pageCount > pageSize)

{

if (byType == OrderByType.Desc)

query = query.OrderByDescending(expression).Skip(Skip).Take(Take);

else

query = query.OrderBy(expression).Skip(Skip).Take(Take);

}

return query;

}

}

publicenum OrderByType

{

Desc = 2,

Asc = 1,

}

 

以上是 EF如何分页最大优化 的全部内容, 来源链接: utcz.com/z/516294.html

回到顶部