I have a standard ASP.NET MVC 3 Controller with an action that has following signature:
public ActionResult Index(int? page, string sort, string sortDir)
My view is using WebGrid so parameters are produced by it automatically.
Next I use Dynamic Expressions API (aka Dynamic LINQ) to convert parameters into query. Example:
var customerSummary = CustomerManager.CustomerRepository.GetQuery()
.OrderBy(sort + " " + sortDir)
.Select(c => new CustomerSummaryViewModel()
{
Id = c.Id,
Name = c.Name,
IsActive = c.IsActive,
OrderCount = c.Orders.Count
})
.Skip(page.Value - 1 * 10) //10 is page size
.Take(10)
.ToList();
The Goal
What I would like to do is to use Dynamic Expressions API itself to validate parameters for sorting (and perhaps create a valid lambda). For example, I'd like to use DynamicExpression.Parse()
or DynamicExpression.ParseLambda()
methods to see if they produce ParseException
, in which case I can replace erroneous params with default (e.g. sort by name ascending "Name ASC")...
The Problem
The problem is that IQueryable
extensions take only a string
If I wanted to use ParseLambda
and then feed it to .OrderBy
I cannot use direction (it takes in only property name). For example, I can do this:
var se = DynamicExpression.ParseLambda<Customer, string>("Name"); // now I can use .OrderBy(se) which is same as .OrderBy(c=>c.Name)
but not this
var se = DynamicExpression.ParseLambda<Customer, string>("Name DESC");
Recap
I would like to use Dynamic LINQ to 1) validate and 2) build predicates (for sorting) based on action parameters