【问题标题】:Building an OrderBy expression using the name of a property使用属性名称构建 OrderBy 表达式
【发布时间】:2011-09-20 16:16:15
【问题描述】:

我正在尝试通过 MVC3 中的 WebGrid 控件支持排序,该控件通过 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'

【问题讨论】:

  • 您是否尝试过使用 Expression.Convert,如下所示:stackoverflow.com/questions/2200209/…
  • 我刚刚使用Expression.TypeAs 让它工作。我不确定这两者之间的区别是什么,但如果您想将其作为答案提交,我将非常乐意为您提供信用。
  • 很高兴您的问题得到解决。我不确定两者之间的区别是什么!

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


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 2012-07-13
    • 1970-01-01
    • 2013-08-21
    • 1970-01-01
    • 2020-05-04
    • 2021-11-29
    • 1970-01-01
    • 2013-08-17
    • 1970-01-01
    相关资源
    最近更新 更多