0

I want to create a generic repository, and have a method that returns an IPagedList like the following:

    public IPagedList<TEntity> GetPage(int? page, int? size)
    {
        IQueryable<TEntity> query = _dbSet; // DbSet<TEntity> _dbSet;
        return query.ToPagedList(page ?? 1, size ?? 10);
    }

However, IPagedList requires to add an OrderBy() or it throws the following message:

The method 'Skip' is only supported for sorted input in LINQ to Entities. The method 'OrderBy' must be called before the method 'Skip'.

How can i achieve this, how can i add ordering for TEntity type? I can have the method return IQueryable and do the paging on controller / caller and it works, but wanted to do this on the generic repository.

Mentor
  • 495
  • 1
  • 4
  • 18

1 Answers1

1

Make your TEntity more specific as in implementing either an abstract base class or an interface then update you method signature to reflect this.

To illustrate I have a mode class called Blog which implements interface IEntity

public interface IEntity
{
    Int32 Id { get; set; }
}
public class Blog : IEntity
{
    public int Id { get; set; }
    public String Name { get; set; }
}

Then you could update your Method signature like so:

public IPagedList<TEntity> GetPage<TEntity>(int? page, int? size) where TEntity : IEntity
{
    IQueryable<TEntity> query = _dbSet; // DbSet<TEntity> _dbSet;
    return query.OrderBy(x => x.Id).ToPagedList(page ?? 1, size ?? 10);
}

Alternatively you could use the handy Extension method from here Dynamic Linq OrderBy.

Then you could update your method signature to be

public IPagedList<TEntity> GetPage<TEntity>(int? page, int? size, string orderBy) where TEntity : IEntity
{
    IQueryable<TEntity> query = _dbSet; // DbSet<TEntity> _dbSet;
    return query.OrderBy(orderBy).ToPagedList(page ?? 1, size ?? 10);
}

You could easily extend this to also take sort direction into consideration

Community
  • 1
  • 1
Drauka
  • 1,189
  • 1
  • 9
  • 20
  • It should work in this case. However, in my case changing the domain models is not an option, and the primary keys are not named the same. – Mentor Mar 06 '14 at 23:10