How to use Order By in this MSDN example

纵然是瞬间 提交于 2019-12-22 03:58:18

问题


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:


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));


来源:https://stackoverflow.com/questions/10935077/how-to-use-order-by-in-this-msdn-example

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!