This is my query, how can I use string as orderby parameter?
string sortColumn=\"Title\";
var items = (from ltem in ctxModel.Items
where ltem.Ite
Here's another alternative, the EntitySorter. Allows a bit what dynamic LINQ does with strings, but wraps the operation in a object, just like with the Query Object pattern. It allows both sorting by strings, and by type safe constructs. Here are some examples:
// Ways of defining an entity sorter
// 1. Using strings:
IEntitySorter sorter = EntitySorter
.OrderBy("Address.City")
.ThenByDescending("Id");
// 2. Defining a sorter with lambda's
IEntitySorter sorter = EntitySorter
.OrderByDescending(p => p.Name)
.ThenBy(p => p.Id)
.ThenByDescending(p => p.Address.City);
// 3. Using a LINQ query
IEntitySorter sorter =
from person in EntitySorter.AsQueryable()
orderby person.Name descending, person.Address.City
select person;
// And you can pass a sorter from your presentation layer
// to your business layer, and you business layer may look
// like this:
static Person[] GetAllPersons(IEntitySorter sorter)
{
using (var db = ContextFactory.CreateContext())
{
IOrderedQueryable sortedList =
sorter.Sort(db.Persons);
return sortedList.ToArray();
}
}
You can find the code here.