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对象一起使用.
谢谢你的帮助
总结以上是内存溢出为你收集整理的c# – Dynamic Func,IOrderedQueryable> Expression全部内容,希望文章能够帮你解决c# – Dynamic Func,IOrderedQueryable> Expression所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)