how to order by a dynamic column name in EntityFramework?

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

Question

I am attempting to make the following code function; it was previously working with MSSQL, but after switching to mySQL it is not.

  records.Content = db.areas
                         .Where(x =>   x.Name.Contains(filter)))
                         .OrderBy("dated desc") 
                         .ToList();

I see the error "One or more of the required types could not be loaded. For further details, get the LoaderExceptions property."

string colName = "datedD" ; 

How should I sort based on the colName variable?
`

1
4
6/27/2016 1:37:41 PM

Accepted Answer

Try it.

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

We may use the in.Net CoreEF.Property technique to enter the property's name 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





Related

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