How to use an Argument in NewExpression as Expression to be used in OrderBy method?
First, I use C# 4.0 and 开发者_运维知识库EF 4.0 with POCO object to access database. Next, I create some grid (like jqGrid) for displaying data from database via ASP.NET MVC 2.0. This grid can order data by clicking at the column header. Source code could look like this.
// This method will generate data for jqGrid request.
// jqGridRequest contain several options about how to query data like
// Take 10 result
// Skip 50 rows
// Filter by something
// Order by column name
public JsonResult GetPeopleData(jqGridRequest req)
{
// This extension method has 2 parameters that are jqGridRequest and
// Expression<Func<T, object>> for creating object to be serialized.
// In this case, T is People type.
return DataContext.People.AsJqGridResult
(
req,
x => new
{
x.ID,
Name = x.FirstName + " " + x.LastName,
x.Age
}
)
}
Everything works fine. The question is when I try to order "Name" column in this grid, jqGrid will send the request that tell controller to order data by "Name" column. However, "Name" column does not exist on database because it's just a combined value of some column.
The easiest to solve this question is creating some code for doing something like the following code.
DataContext.People.OrderBy(x => x.FirstName + " " + x.LastName);
However, I need to create some method to handle any simple orderby condition like this. After I search and try any possibilities about expression. I just found that I can use some data that is contained in NewExpression to order this query. But I do not know how to convert/create Argument in NewExpression object to Expression for using as OrderBy method parameter.
Thanks
Name
doesn't exist on the DB, but it does exist in the anonymous type you're projecting onto.
I'm not going to try and guess about what all your extension methods do. But if you did:
var q = from p in DataContext.People
select new
{
Name = p.FirstName + " " + p.LastName
};
...and then:
var r = q.OrderBy(p => p.Name);
...then it should "just work".
精彩评论