问题
I am trying to get following code working , This was working fine for MSSQL , but since i changed to use mySql it is not working
records.Content = db.areas
.Where(x => x.Name.Contains(filter)))
.OrderBy("dated desc")
.ToList();
I get the error " Unable to load one or more of the requested types. Retrieve the LoaderExceptions property for more information."
string colName = "datedD" ;
how to order by depneding on colName variable ?
`
回答1:
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();
回答2:
In asp.net mvc core 2, you 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));
I'm not sure from which version we can use this.
来源:https://stackoverflow.com/questions/38055150/how-to-order-by-a-dynamic-column-name-in-entityframework