使用属性的名称构建OrderBy表达式

时间:2011-09-20 16:16:16

标签: c# asp.net-mvc reflection expression-trees

我正在尝试通过MVC3中的WebGrid控件来支持排序,MVC3通过sort参数将模型上的属性名称传递给我的操作。

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);
}

当我尝试按Name属性(string类型)对模型进行排序时,此代码有效。但是,如果我尝试按Id排序,则会收到错误Expression of type 'System.Int32' cannot be used for return type 'System.Object'

1 个答案:

答案 0 :(得分:2)

您可以使用Expression.Convert来执行拳击。