按任何 属性 对可查询对象进行排序的更好方法

Better way to Sort a Queryable by any property

这种情况类似于,但在这种情况下,在执行方法'.ToList()'之前内存中没有列表。

我想在执行数据库查询之前进行排序。我想'write'在执行前SQL查询。

我的代码:

public virtual DataTablesData<TViewModel> DataTablesGetData(DataTablesParam model)
{
    var paged = new DataTablesData<TViewModel>();
    IQueryable<TEntity> qr;

    try
    {
        using (var db = new EdmxMSSQLContainer())
        {
            List<TViewModel> list = null;

            qr = db.Set<TEntity>();

            int iColumn = model.Order.FirstOrDefault().Column;
            var property = typeof(TEntity).GetProperty(model.Columns.ToArray()[iColumn].Data);
            var param = Expression.Parameter(typeof(TEntity));
            Expression final = Expression.Property(param, property);

            if (property.PropertyType.IsValueType)
            {
                final = Expression.MakeUnary(ExpressionType.Convert, final, typeof(object));
            }

            var lambda = Expression.Lambda<Func<TEntity, object>>(final, param);

            if (model.Order.FirstOrDefault().Dir.Equals("asc"))
            {
                qr = qr.OrderBy(lambda);
            }
            else
            {
                qr = qr.OrderByDescending(lambda);
            }

            // THIS LINE THROW EXCEPTION
            // qr.ToList() execute SQL Query
            list = Mapper.Map(qr.ToList(), list);

            paged.recordsTotal = this.CountRecords();
            paged.recordsFiltered = list.Count();
            paged.data = list;
        }
    }
    catch (Exception ex)
    {
        OnError(ex);
    }

    return paged;
}

这一行抛出异常:

list = Mapper.Map(qr.ToList(), list);

异常:

Unable to cast the type System.Int32 to type System.Object. LINQ to Entities only supports casting EDM primitive or enumeration types

我找到了更好的方法。我必须执行以下步骤:

1 - 在项目中添加包 "Linq Dynamic":

Install-Package System.Linq.Dynamic.Library

2 - 在 Class 中导入包:

using System.Linq.Dynamic;

3 - 可按字符串名称查询的订单 属性:

qr.OrderBy(stringPropertyName);                 //asc
qr.OrderBy(stringPropertyName + " descending"); //des

它非常适合我。

你可以试试这个:

    Func<IQueryable<Entity>, IOrderedQueryable<Entity>> orderBy = query => query.OrderBy(e => e.ID);

                Expression<Func<Entity, bool>> fitler = e => e.Active;  


public virtual IEnumerable<T> Get(Expression<Func<T, bool>> filter = null, Func<IQueryable<T>, IOrderedQueryable<T>> orderBy = null)
            {
                IQueryable<T> query = dbSet;

                if (filter != null)
                    query = query.Where(filter);

                if (orderBy != null)
                    return orderBy(query).ToList();
                else
                    return query.ToList();
            }