I have a GetX(DataTableParameters model) function where model.Order contains Column (which can be 1 (Id), 2 (Name) etc..) and Dir (which can be 'asc' or 'desc'). Then i have a LINQ query where i would like to dynamically generate OrderByDescending or OrderBy and r => r.Id or r => r.Name depending on model values.
DbContext.Users.Where(r => r.FirstName.Contains(model.Search.Value) ||
r.LastName.Contains(model.Search.Value) ||
r.Email.Contains(model.Search.Value))
.**OrderByDescending(r => r.Id)**.Skip(model.Start).Take(model.Length);
Can this be done? If so can anyone point me in the right direction. Thank you for any help.
Use Dynamic Linq, there are a few libraries that help you working with it. I'm using this and it looks great, look here for more info
It's a fork from an older library that was suddenly removed and it allows you to write dynamic code like
var result = myQuery
.OrderBy("Field1 asc")
.Select("new (Field1, Field2)");
take a look at http://web.archive.org/web/20160109203827/http://dynamiclinq.azurewebsites.net/ (documentation for old library) to have a good overview.