Unable to sort with property name in LINQ OrderBy

后端 未结 3 1403
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-12-14 20:55

Error is

LINQ to Entities does not recognize the method \'System.Object GetValue(System.Object, System.Object[])\' method, and this method ca

3条回答
  •  臣服心动
    2020-12-14 21:43

    Just add the following extension to your code and you're good to go:

    using System.Linq;
    using System.Linq.Expressions;
    using System;
    
    namespace SomeNameSpace
    {
        public static class SomeExtensionClass
        {
            public static IQueryable OrderByField(this IQueryable 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(mce);
            }
        }
    

    }

    Usage:

    .OrderByField(sortcriteria, true)
    

    Edit:

    For support for the ThenBy method however the following methods returning an IOrderedQueryable should take care of it all:

    public static class SomeExtensionClass
    {
        private static IOrderedQueryable OrderingHelper(IQueryable 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)source.Provider.CreateQuery(call);
        }
    
        public static IOrderedQueryable OrderBy(this IQueryable source, string propertyName)
        {
            return OrderingHelper(source, propertyName, false, false);
        }
    
        public static IOrderedQueryable OrderBy(this IQueryable source, string propertyName, bool descending)
        {
            return OrderingHelper(source, propertyName, descending, false);
        }
    
        public static IOrderedQueryable ThenBy(this IOrderedQueryable source, string propertyName)
        {
            return OrderingHelper(source, propertyName, false, true);
        }
    
        public static IOrderedQueryable ThenBy(this IOrderedQueryable source, string propertyName, bool descending)
        {
            return OrderingHelper(source, propertyName, descending, true);
        }
    }
    

提交回复
热议问题