Echilon
Echilon

Reputation: 10254

Entity Framework and Sorting

I'm trying to sort a list of entities using a GridView in ASP.NET, but I can't seem to get it working following examples. I have a property called Name on my entity, and I'm trying to sort by a specified column if given, or the Name column if the sortExpression is empty.

public static List<Product> GetProducts(int startRowIndex, int maximumRows, string sortExpression) {
    using(var context = new ShopEntities()) {
        var products = context.Products;
        products.OrderBy("it."+(string.IsNullOrEmpty(sortExpression) ? "Name" : sortExpression))
                                       .Skip(startRowIndex)
                                       .Take(maximumRows);
        return products.ToList();
    }
}

I can't get it to sort though. The only other option seems to be doing a switch on the property name for every property in the entity and using a lambda.

Upvotes: 0

Views: 3322

Answers (1)

Craig Stuntz
Craig Stuntz

Reputation: 126547

OrderBy doesn't mutate the expression. It returns a new expression, which your code ignores. Change your code to:

products = products.OrderBy("it."+ //...

Upvotes: 2

Related Questions