using System.Collections.Generic;
using System.Linq;
using System.Text;
using Migration.Target.Dao.Entities;
namespace Migration.Target.Dao.Filters
{
public sealed class Pager<TEntity>
where TEntity : Entity
{
public int CurrentPage { get; set; }
public int RowsPerPage { get; set; }
public int TotalPages { get; private set; }
public int TotalRows { get; private set; }
internal Pager()
: base()
{
this.CurrentPage = 0;
this.RowsPerPage = 0;
}
internal IQueryable<TEntity> BuildPager(IQueryable<TEntity> query)
{
this.TotalRows = 0;
this.TotalPages = 0;
IQueryable<TEntity> paginatedQuery = query;
bool paginated = (this.RowsPerPage > 0 && this.CurrentPage > 0);
if (paginated)
{
this.TotalRows = query.Count();
//Dado que hay problemas con el soporte de paginado para Access, me veo en la obligacion de adaptar el filtro
int minResults = (this.CurrentPage - 1) * this.RowsPerPage;
int maxResults = (this.CurrentPage * this.RowsPerPage);
var resultRows = query.Take(maxResults).Select(x => x.Id).ToList();
resultRows.RemoveRange(0, resultRows.Count < minResults ? resultRows.Count : minResults);
if (resultRows.Count > 0)
query = query.Where(x => resultRows.Contains(x.Id));
decimal estimatedPages = (decimal)this.TotalRows / (decimal)this.RowsPerPage;
int roundPage = (int)Math.Truncate(estimatedPages);
int extraPage = (this.TotalRows % this.RowsPerPage > 0) ? 1 : 0;
this.TotalPages = roundPage + extraPage;
paginatedQuery = query/*.Skip((this.CurrentPage - 1) * this.RowsPerPage)*/.Take(this.RowsPerPage);
}
return paginatedQuery;
}
}
}
No hay comentarios:
Publicar un comentario