views:

197

answers:

1

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.

+1  A: 

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

products = products.OrderBy("it."+ //...
Craig Stuntz
Thanks, difficult one to spot. Another thing I'm unsure about is the "it" prefix. It's difficult to google it as it's one of the most common words, but does it just refer to the entity?
Echilon
Yes, "it" is the entity. That's only for Query Builder methods.
Craig Stuntz