使用属性名称构建OrderBy表达式 [英] Building an OrderBy expression using the name of a property

查看:111
本文介绍了使用属性名称构建OrderBy表达式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图通过MVC3中的WebGrid控件支持排序,该控件通过sort参数将模型上属性的名称传递给我的操作.

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

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

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'.

推荐答案

您可以使用Expression.Convert进行装箱.

这篇关于使用属性名称构建OrderBy表达式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆