How to dynamically order by certain entity properties in Entity Framework 7 (Core)

前端 未结 1 537
醉酒成梦
醉酒成梦 2020-12-18 03:17

I have a project where the front-end JavaScript specifies a list of columns to order by.

Then in the back-end I have multi-layer application. Typical scenario

<
1条回答
  •  醉话见心
    2020-12-18 03:57

    FromSql definitely cannot be used to mix SQL. So as usual with dynamic queries, you have to resort to System.Linq.Expressions.

    For instance, something like this:

    public static class QueryableExtensions
    {
        public static IQueryable OrderBy(this IQueryable source, IEnumerable sortModels)
        {
            var expression = source.Expression;
            int count = 0;
            foreach (var item in sortModels)
            {
                var parameter = Expression.Parameter(typeof(T), "x");
                var selector = Expression.PropertyOrField(parameter, item.ColId);
                var method = string.Equals(item.Sort, "desc", StringComparison.OrdinalIgnoreCase) ?
                    (count == 0 ? "OrderByDescending" : "ThenByDescending") :
                    (count == 0 ? "OrderBy" : "ThenBy");
                expression = Expression.Call(typeof(Queryable), method,
                    new Type[] { source.ElementType, selector.Type },
                    expression, Expression.Quote(Expression.Lambda(selector, parameter)));
                count++;
            }
            return count > 0 ? source.Provider.CreateQuery(expression) : source;
        }
    }
    

    And then:

    var thingsQuery = _context.Things
            .Include(t => t.Other)
            .Where(t => t.Deleted == false)
            .OrderBy(sortModels);
    

    0 讨论(0)
提交回复
热议问题