how to order by a dynamic column name in EntityFramework?

Kas picture Kas · Jun 27, 2016 · Viewed 8.3k times · Source

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 ?
`

Answer

S.Serpooshan picture S.Serpooshan · Jul 23, 2018

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