0

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 Answer 1

2

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

products = products.OrderBy("it."+ //...
Sign up to request clarification or add additional context in comments.

2 Comments

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?
Yes, "it" is the entity. That's only for Query Builder methods.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.