How to fix 'No property or field exists in type' error?

asp.net-mvc c# dynamic-linq entity-framework linq

Question

I got this error when trying to sort any columns that are not in the Order table, if I use OrderBy("Customer.CompanyName" + " " + sortDir) the error will gone but all the columns will become unable to sort. The OrderBy method used below come from here.

What is the cause of the problem ?

    public ActionResult WebGrid(int page = 1, int rowsPerPage = 10, string sortCol = "OrderID", string sortDir = "ASC")
    {
        List<Order> res;
        using (var nwd = new NorthwindEntities())
        {
             var _res = nwd.Orders
                .OrderBy(sortCol + " " + sortDir)
                .Select(o => new Order
                {
                    OrderID = o.OrderID,
                    OrderDate = o.OrderDate,
                    CompanyName = o.Customer.CompanyName,
                    FirstName = o.Employee.FirstName,
                    //......
                    //......
                    //......
                });
1
2
9/11/2016 6:39:06 AM

Accepted Answer

The class you provided the link to is marked as internal and it can't be used outside the assembly it was defined in, so you can't use it in your code.

This API supports the product infrastructure and is not intended to be used directly from your code. Provides functionality to create new classes from values in a LinqDataSource control.

So What you're actually trying to use is OrderBy inside Queryable class which is part of System.Linq which can be used as following:

.OrderBy(x=> x.sortCol + " " + x.sortDir)

If you're trying to order by two columns, then you can use:

.OrderBy(x=> x.sortCol).ThenBy(x=> x.sortDir)

If you want to dynamically specify the OrderBy expression, you can either do a switch statement for each possible parameter, or follow this SO Answer to build a dynamic Expression Tree.

5
5/23/2017 12:32:47 PM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow