Spent all day trying to find ready to use solution for "Sort data in LINQ bases on Query String" without any results.
SO, I have a LINQ query in action:
public AcrionResult MyAction(int perPage = 10, string orderBy = "DESC", sting sortBy = "id")
{
var some = from m in db.Some select new ExampleModel {id = m.id, some = m.some};
return View(some);
}
From exmaple above:
1. perPage describe how many items we should show in page 2. orderBy DESC or ASC order 3. sortBy can be some field from ViewM开发者_C百科odelI need to make somethisng like this:
var query = some.OrderFilter(...).AmountFilter(...).SortByFilter(...)
Can somebody help me?
Thanks a lot!
You could use dynamic LINQ. Here's another example of implementing dynamic queries.
The page size is best handled by Take
and Skip
– LINQ to Entities will translate that in to SQL.
The parametrised sort can be done either by creating an expression tree based on the selected property and passing it to OrderBy
or OrderByDescending
as needed. Or by using Entity-LINQ building the SQL from the name of the field.
The latter apporoach needs to white-list the column names to avoid SQL Injection..
精彩评论