Pagination with generic method

Asked

Viewed 379 times

3

I am trying to create a generic method for paging, I tried to do as the code below, but when using Skip I need to have a orderby and I’m not sure how to do.

public IQueryable<TEntity> GetPaginacao(int PageStart, int PageSize)
        {
            return Db.Set<TEntity>()
                .Take(PageSize)
                .Skip(PageStart * PageSize)
                .AsNoTracking();

        }

Error:

The method 'Orderby' must be called before the method 'Skip'

1 answer

7


No need to reinvent the wheel. Just install this package.

Use:

var pagina = 1;
var registros = 50;
var selecao = db.Entidade.ToPagedList(pagina, registros);

Or else:

var selecao = await db.Entidade.ToPagedListAsync(pagina, registros);

I guess your case is gonna have to be ordered by something:

var selecao = db.Entidade.OrderBy(e => e.Id).ToPagedList(pagina, registros);
  • Pagedlist returns an Ipagedlist type, how do I convert it to Iqueryable or Ienumerable ? or would it be better to work with List() ?

  • IPagedList implements IEnumerable. Should not impact your old code.

  • Changing the original code to return Db.Set<TEntity>().ToPagedList(1, 10); an error is presented Cannot implicitly Convert type 'Pagedlist.Ipagedlist<Tentity>' to 'System.Linq.Iqueryable<Tentity>'. An Explicit Conversion exists (are you Missing a cast?) I tried to change to public IList<TEntity> GetPaginacao(int PageStart, int PageSize) return Db.Set<TEntity>().ToPagedList(1, 10).ToList(); and the following error is displayed The method 'Skip' is only supported for Sorted input in LINQ to Entities. The method 'Orderby' must be called before the method 'Skip'.

  • Ah, yes. I changed the answer. I wouldn’t do this method GetPaginacao. It is unnecessary, because the intention of you to envelop the procedure is precisely not to use Skip() and Take() all the time, but now there’s no reason.

  • I think I understand, but I’m having some doubts about performance, whenever we find examples of paging, it’s something like this: var x = db.entidade.GetAll(); return x.ToPagedList(1, 10); in this case, when I call Getall() I’m not bringing all the bank records?

  • This example is not good at all. It’s just the initial example.

Show 1 more comment

Browser other questions tagged

You are not signed in. Login or sign up in order to post.