how to order by a dynamic column name in EntityFramework?
Try this
string filterString = "dated";
bool isAscSorting = false;
Func<dynamic, dynamic> orderingFunction = i =>
filterString == "dated" ? i.dated :
filterString == "something" ? i.columnx : "";
records.Content = (isAscSorting) ?
db.areas
.Where(x => x.Name.Contains(filter)))
.OrderBy(orderingFunction)
.ToList()
:
db.areas
.Where(x => x.Name.Contains(filter)))
.OrderByDescending(orderingFunction)
.ToList();
In .Net Core, we can use the EF.Property
method to specify the name of the property as a string:
string sortColumn = "Price";
//IQueryable<Product> q = from p in myDbContext.Products select p;
q = q.OrderBy(p => EF.Property<object>(p, sortColumn));