Retrocoder
Retrocoder

Reputation: 4713

Repository pattern how to define an OrderBy

I have a repository class that is very generic in its use and doesn't refer to my tables specifically. Shown below is one of the functions to get all the items in a table. What I would like to do is to extend this so that the result can be ordered. Is there a way to pass in a predicate / expression or something similar?

public IQueryable<T> All<T>() where T : class
{
    return _context.Set<T>().AsQueryable();
}

Upvotes: 4

Views: 2509

Answers (1)

Sergey Berezovskiy
Sergey Berezovskiy

Reputation: 236228

Simply use Queryable.OrderBy method on your all entities:

fooRepository.All().OrderBy(foo => foo.Bar)

If you want to add method with predicate:

public IQueryable<T> AllOrderedBy<T,TKey>(Expression<Func<T,TKey>> predicate) 
    where T : class
{
    return _context.Set<T>().OrderBy(predicate);
}

BTW DbSet<T> implements IQueryable<T>, so you don't need to call AsQueryable().

Upvotes: 4

Related Questions