views:

65

answers:

1

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

A: 

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

Craig Stuntz
I know it can write something like this. But it does not what I want for this question. I need some method to convert binary expression (like x.col1 + ' ' + x.col2) to expression that can be used in OrderBy method.However, if everyone cannot solve this question, I will use something like your suggestion to solve this answer.
Soul_Master
You can write `Expression<Func<Person, string>> nameExp = p => p.FirstName + " " + p.LastName` You can then do `.OrderBy(nameExp)` and that will convert to SQL. But notice I'm using `Person` here; this won't work with an anonymous type.
Craig Stuntz