Generate EF orderby expression by string

前端 未结 5 1496
不思量自难忘°
不思量自难忘° 2020-11-29 05:27

I want to generate expression by string parameter,some code like:

private Expression> Generate(string orderby)
{
    switch (orderb         


        
5条回答
  •  失恋的感觉
    2020-11-29 06:03

    I referred to the old System.Linq.Dynamic codebase in CodePlex and created a quite simple version from the perspective of implementation and invocation. Of course, it's an extension method on IQueryable

    /*
    using System;
    using System.Linq;
    using System.Linq.Expressions;
    */
    
    public static IQueryable OrderBy(this IQueryable query, string orderByExpression)
    {
        if (string.IsNullOrEmpty(orderByExpression))
            return query;
    
        string propertyName, orderByMethod;
        string[] strs = orderByExpression.Split(' ');
        propertyName = strs[0];
    
        if (strs.Length == 1)
            orderByMethod = "OrderBy";
        else
            orderByMethod = strs[1].Equals("DESC", StringComparison.OrdinalIgnoreCase) ? "OrderByDescending" : "OrderBy";
    
        ParameterExpression pe = Expression.Parameter(query.ElementType);
        MemberExpression me = Expression.Property(pe, propertyName);
    
        MethodCallExpression orderByCall = Expression.Call(typeof(Queryable), orderByMethod, new Type[] { query.ElementType, me.Type }, query.Expression
            , Expression.Quote(Expression.Lambda(me, pe)));
    
        return query.Provider.CreateQuery(orderByCall) as IQueryable;
    }
    

    Here is samples how to use it, tested for Entity Framework Core 3:

    IQueryable query = dbContext.People;
    query = query.OrderBy("FirstName"); // ORDER BY FirstName
    
    IQueryable query = dbContext.People;
    query = query.OrderBy("FirstName ASC"); // ORDER BY FirstName
    
    IQueryable query = dbContext.People;
    query = query.OrderBy("FirstName DESC"); // ORDER BY FirstName DESC
    

提交回复
热议问题