Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to sorting dynamic in lambda entity framework?

I want to sort dynamic in lambda entity framework.I founded it more time, but seem not work.

////string column_name // the name of column in table   <<< don't care this, I finished
////string sort_order  // ASC or DESC    <<< don't care this, I finished

using (var db = new ABCEntities())
{
    // get dynamic type of column name , but i can not 
    // ???????????
    var columnExp = typeof(LOCATION).GetProperty(column_name);

    IEnumerable<LOCATION> query = db.LOCATIONs;
    if(sort_order = "ASC")
    {
        query = query.OrderBy(columnExp).Tolist();  
    }
    else
        query = query.OrderByDescending(columnExp).Tolist();    
}

I try with follow

query = db.LOCATIONs.OrderByDescending(q => q.GetType().GetProperty(column_name).GetValue(q, null)).ToList();

But get error at

LINQ to Entities does not recognize the method 'System.Object GetValue(System.Object, System.Object[])' method, and this method cannot be translated into a store expression

Can you tell me some mistake or wrong and how to fix it ? Thank you so much.

like image 492
Brian Crist Avatar asked Dec 24 '15 02:12

Brian Crist


1 Answers

How about use Dynamic Linq ? It can generate query from string.

using (var db = new ABCEntities()){
  var columnExp = "columnName";
  var query = db.LOCATIONs;
  if(sort_order = "ASC")
  {
      query = query.OrderBy(columnExp).Tolist();  
  }
  else
  {
      query = query.OrderByDescending(columnExp).Tolist();
  }
}
like image 54
kcwu Avatar answered Oct 07 '22 19:10

kcwu