使用属性名称构建 OrderBy 表达式
我试图通过 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
排序,则会收到错误“System.Int32”类型的表达式不能用于返回类型“System.Object”
。
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'
.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您可以使用
Expression.Convert
来执行装箱。you could use
Expression.Convert
to perform Boxing.