Building an OrderBy expression using the name of a

2019-07-04 01:35发布

问题:

I'm trying to support sorting via the WebGrid control in MVC3, which passes the name of a property on my model into my actions via a sort parameter.

public class Agent {
    public int Id { get; set; }
    public string Name { get; set; }
}

[HttpGet]
public ActionResult Index(string sort = "Id", string sortdir = "ASC") {

    // Define the parameter that we are going to use in the OrderBy clause.
    var param = Expression.Parameter(typeof(Agent), "agent");

    // Now we'll make our lambda function that returns the
    // property's value by it's name.
    var sortExpression = Expression.Lambda<Func<Agent, object>>(Expression.Property(param, sort), param);

    var agents = entities.OrderBy(sortExpression).ToList();

    var model = new PagedResult<Agent> {

        CurrentPage = 1,
        PageCount = 1,
        PageSize = DefaultPageSize,
        Results = agents,
        RowCount = agents.Count

    };

    return View(model);
}

This code works when I try to sort my model by the Name property, which is of type string. However, if I try to sort by Id I receive the error Expression of type 'System.Int32' cannot be used for return type 'System.Object'.

回答1:

you could use Expression.Convert to perform Boxing.