Search code examples
c#mysqlasp.net-mvcentity-frameworkdynamic-linq

How to order by a dynamic column name in EntityFramework?


I am trying to get following code working , This was working fine for SQL Server, 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 depending on colName variable?


Solution

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