如何在lambda实体框架中动态排序

本文关键字:动态 排序 框架 实体 lambda | 更新日期: 2023-09-27 18:27:52

我想在lambda实体框架中进行动态排序。我创建了更多的时间,但似乎不起作用。

////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();    
}

我尝试跟随

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

但是出现错误

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

你能告诉我一些错误或错误以及如何解决吗?非常感谢。

如何在lambda实体框架中动态排序

使用Dynamic Linq怎么样?它可以根据字符串生成查询。

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