how to order by a dynamic column name in EntityFramework?

asp.net-mvc c# dynamic-linq entity-framework mysql

Question

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
4
6/27/2016 1:37:41 PM

Accepted Answer

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();
4
6/27/2016 1:41:34 PM

Popular Answer

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));


Related Questions





Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow