10

I'm trying to figure out how to use this orderBy parameter. I am not sure what I am suppose to pass in.

http://www.asp.net/mvc/tutorials/getting-started-with-ef-using-mvc/implementing-the-repository-and-unit-of-work-patterns-in-an-asp-net-mvc-application

   public virtual IEnumerable<TEntity> Get(
        Expression<Func<TEntity, bool>> filter = null,
        Func<IQueryable<TEntity>, IOrderedQueryable<TEntity>> orderBy = null,
        string includeProperties = "")
    {
        IQueryable<TEntity> query = dbSet;

        if (filter != null)
        {
            query = query.Where(filter);
        }

        foreach (var includeProperty in includeProperties.Split
            (new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries))
        {
            query = query.Include(includeProperty);
        }

        if (orderBy != null)
        {
            return orderBy(query).ToList();
        }
        else
        {
            return query.ToList();
        }
    }

1 Answer 1

18

If you read this from the msdn article

"The code Func, IOrderedQueryable> orderBy also means the caller will provide a lambda expression. But in this case, the input to the expression is an IQueryable object for the TEntity type. The expression will return an ordered version of that IQueryable object. For example, if the repository is instantiated for the Student entity type, the code in the calling method might specify q => q.OrderBy(s => s.LastName) for the orderBy parameter."

Its saying when you call the Get you should provide a lambda expression which will be a Func or function on the IQueryable providing an IOrderedQueryable.

So for the Student object used in the article you mite use.

var students = repository.Get(x => x.FirstName = "Bob",q => q.OrderBy(s => s.LastName));
3
  • 1
    Actually, I did read it, but I don't understand it. I kept getting errors. Intellisense actually confused me is why I didn't get the right answer. Thanks.
    – xivo
    Jun 7, 2012 at 15:50
  • Do you guys know how to set the OrderBy to ASC or DESC? Aug 24, 2012 at 16:52
  • 1
    @user1477388 es there is an OrderBy method which is asc and and OrderByDescending method too. Aug 28, 2012 at 11:47

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.