【问题标题】:Unable to sort with property name in LINQ OrderBy无法在 LINQ OrderBy 中使用属性名称进行排序
【发布时间】:2015-05-20 22:52:58
【问题描述】:

错误是

LINQ to Entities 无法识别方法“System.Object” GetValue(System.Object, System.Object[])' 方法,以及这个方法 无法翻译成商店表达式。

我的代码是

public static GridResult GetAllUsers(int count, int tblsize,string sortcreteria)
{
      using (UserEntities entity = new UserEntities())
      {

          var data = entity.User_Details.Take(count)
.OrderBy(i =>.GetType().GetProperty(sortcreteria).GetValue(i,null))
.Skip(tblsize).ToList();
          result.DataSource = data;
          result.Count = entity.User_Details.Count();
      }
      return result;
}

如何将属性名作为字符串进行排序?

【问题讨论】:

标签: c# linq entity-framework linq-to-entities entity-framework-5


【解决方案1】:

只需将以下扩展添加到您的代码中即可:

using System.Linq;
using System.Linq.Expressions;
using System;

namespace SomeNameSpace
{
    public static class SomeExtensionClass
    {
        public static IQueryable<T> OrderByField<T>(this IQueryable<T> q, string SortField, bool Ascending)
        {
            var param = Expression.Parameter(typeof(T), "p");
            var prop = Expression.Property(param, SortField);
            var exp = Expression.Lambda(prop, param);
            string method = Ascending ? "OrderBy" : "OrderByDescending";
            Type[] types = new Type[] { q.ElementType, exp.Body.Type };
            var mce = Expression.Call(typeof(Queryable), method, types, q.Expression, exp);
            return q.Provider.CreateQuery<T>(mce);
        }
    }

}

用法:

.OrderByField(sortcriteria, true)

编辑:

为了支持 ThenBy 方法,但是以下返回 IOrderedQueryable 的方法应该可以解决所有问题:

public static class SomeExtensionClass
{
    private static IOrderedQueryable<T> OrderingHelper<T>(IQueryable<T> source, string propertyName, bool descending, bool anotherLevel)
    {
        var param = Expression.Parameter(typeof(T), "p");
        var property = Expression.PropertyOrField(param, propertyName);
        var sort = Expression.Lambda(property, param);

        var call = Expression.Call(
            typeof(Queryable),
            (!anotherLevel ? "OrderBy" : "ThenBy") + (descending ? "Descending" : string.Empty),
            new[] { typeof(T), property.Type },
            source.Expression,
            Expression.Quote(sort));

        return (IOrderedQueryable<T>)source.Provider.CreateQuery<T>(call);
    }

    public static IOrderedQueryable<T> OrderBy<T>(this IQueryable<T> source, string propertyName)
    {
        return OrderingHelper(source, propertyName, false, false);
    }

    public static IOrderedQueryable<T> OrderBy<T>(this IQueryable<T> source, string propertyName, bool descending)
    {
        return OrderingHelper(source, propertyName, descending, false);
    }

    public static IOrderedQueryable<T> ThenBy<T>(this IOrderedQueryable<T> source, string propertyName)
    {
        return OrderingHelper(source, propertyName, false, true);
    }

    public static IOrderedQueryable<T> ThenBy<T>(this IOrderedQueryable<T> source, string propertyName, bool descending)
    {
        return OrderingHelper(source, propertyName, descending, true);
    }
}

【讨论】:

  • 不应该返回IOrderedQueryable吗?
  • 感谢您指出。我编辑了代码,使其支持IOrderedQueryable 提供的ThenBy 方法。
  • 很好的解决方案。在使用搜索方法做 web api 时,它真的帮助了我。
【解决方案2】:

您可以尝试使用(有些旧的)Dynamic LINQ 库来执行此操作:

var data = entity.User_Details
    .Take(count)
    .OrderBy(sortcriteria)
    .Skip(tblsize)
    .ToList();

或者,您仍然可以使用原始查询对序列进行排序,方法是先将对象移动到内存中,因为 LINQ to Entities 提供程序无法将对反射 API 的调用转换为 SQL:

var data = entity.User_Details
    .Take(count)
    .Skip(tblsize)
    .AsEnumerable()
    .OrderBy(i => i.GetType().GetProperty(sortcriteria).GetValue(i, null))

【讨论】:

  • 你认为 GetValue(i, null) 给出了一个属性名吗?错误说“LINQ to Entities 无法识别”所以你认为你的会转向 SQL 吗?
  • @DavutGürbüz 调用 AsEnumerable()(或任何方法 ToList()、ToArray() 等)强制针对数据库评估 LINQ 查询,这将导致生成的序列为搬进了记忆。从那里您可以轻松地按具有指定名称的属性的值对对象进行排序。
  • 哦。我没看到。当然可以,但是枚举会迭代所有数据,因此在许多情况下它不会是一个真实的场景。
  • 过滤仍然会在数据库中进行,因此只有匹配的对象在排序之前被移动到内存中。我想说,这是一个公平的权衡。
  • 动态查询就可以了。对于 where 条件,我更喜欢 LinqKit。如果条件不依赖于迭代项。我们为什么不首先生成标准拳头并在实际表达中使用它。 “i.GetType().GetProperty(sortcriteria)”部分总是返回相同的东西。我不明白 GetValue 是什么; 3 ,5 我问它会返回属性名称!
【解决方案3】:

您可能需要使用Expression Trees 来构造Linq 语句OrderBy(x =&gt; x.SomeProperty)。

Create an OrderBy Expression for LINQ/Lambda

Create LINQ to entities OrderBy expression on the fly

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-09-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-05-13
    • 1970-01-01
    相关资源
    最近更新 更多