【问题标题】:How to sorting dynamic in lambda entity framework?如何在 lambda 实体框架中进行动态排序?
【发布时间】:2016-03-30 12:22:54
【问题描述】:

我想在 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

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

【问题讨论】:

  • 我试了一下,还是不行。
  • @BrianCrist 请更具体。 什么不起作用?我认为您应该简单地执行OrderBy(column_name),假设您使用的是动态 LINQ。

标签: c# entity-framework sorting lambda sql-order-by


【解决方案1】:

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

【讨论】:

  • 使用 Dynamic Linq,然后像上面一样修改你的代码。还是粘贴更多代码?
  • 亲爱的kcwu,你的回答很有帮助,另外,我创建了一个方法var propertyInfo = typeof(LOCATION).GetProperty(columnName); query = db.LOCATIONs.AsEnumerable().OrderByDescending(x =&gt; propertyInfo.GetValue(x, null)).ToList();。谢谢
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多