c# – Dynamic Func,IOrderedQueryable> Expression

前端之家收集整理的这篇文章主要介绍了c# – Dynamic Func,IOrderedQueryable> Expression前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我正在使用这里提到的模式
http://www.asp.net/mvc/tutorials/getting-started-with-ef-using-mvc/implementing-the-repository-and-unit-of-work-patterns-in-an-asp-net-mvc-application

我正在使用下面的方法查询EF

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

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

        foreach (var includeProperty in includeProperties.Split
            (new char[] { ',' },StringSplitOptions.RemoveEmptyEntries))
        {
            query = query.Include(includeProperty);
        }

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

现在我想创建动态Func< IQueryable< TEntity>,IOrderedQueryable< TEntity>>表达式来订购我的数据.

我只知道字段名称为字符串和顺序类型(升序,降序)为字符串(asc,desc)

解决方法

最后我可以写出我想要的方法.
public static Func<IQueryable<TEntity>,IOrderedQueryable<TEntity>> GetOrderBy(string orderColumn,string orderType) {
            Type typeQueryable = typeof(IQueryable<TEntity>);
            ParameterExpression argQueryable = Expression.Parameter(typeQueryable,"p");
            var outerExpression = Expression.Lambda(argQueryable,argQueryable);
            string[] props = orderColumn.Split('.');
            IQueryable<TEntity> query = new List<TEntity>().AsQueryable<TEntity>();
            Type type = typeof(TEntity);
            ParameterExpression arg = Expression.Parameter(type,"x");

            Expression expr = arg;
            foreach(string prop in props) {
                PropertyInfo pi = type.GetProperty(prop,BindingFlags.IgnoreCase | BindingFlags.Public | BindingFlags.Instance);
                expr = Expression.Property(expr,pi);
                type = pi.PropertyType;
            }
            LambdaExpression lambda = Expression.Lambda(expr,arg);
            string methodName = orderType == "asc" ? "OrderBy" : "OrderByDescending";

            MethodCallExpression resultExp =
                Expression.Call(typeof(Queryable),methodName,new Type[] { typeof(TEntity),type },outerExpression.Body,Expression.Quote(lambda));
            var finalLambda = Expression.Lambda(resultExp,argQueryable);
            return (Func<IQueryable<TEntity>,IOrderedQueryable<TEntity>>)finalLambda.Compile();
        }

方法有两个参数,第一个是字段名,另一个是asc或desc.
方法的结果可以直接与IQueryable对象一起使用.

谢谢你的帮助

原文链接:https://www.f2er.com/csharp/97778.html

猜你在找的C#相关文章