Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use Order By in this MSDN example

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();
        }
    }
like image 561
xivo Avatar asked Jun 07 '12 15:06

xivo


1 Answers

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));
like image 194
Richard Forrest Avatar answered Oct 27 '22 04:10

Richard Forrest