日期:2014-05-20  浏览次数:20850 次

[Entity Framework] Orderby问题
前端传递过来 排序列的值 
如何转为查询语句

C# code
public PagedList<T> GetManyPage(QueryModel query,PageSelect pageSel)
    {
        Type type = typeof(T);
        var key = type.GetProperty(pageSel.OrderByKey);
        
        ParameterExpression param = Expression.Parameter(typeof(T), "c");
        MemberExpression paramKey = Expression.Property(param, pageSel.OrderByKey);
        
        //var expression = Expression.Lambda<Func<T, TKey>>(paramKey, param);
        
        if (pageSel.Direction == Direction.asc)
        {
            //return dbset.Where(query).OrderBy(c => pageSel.OrderByKey).ToPagedList(pageSel.CurrentPage, pageSel.PageSize);

            return dbset.Where(query).OrderBy(c => key).ToPagedList(pageSel.CurrentPage, pageSel.PageSize);
            //return dbset.Where(query).OrderByDescending(c => key).ToPagedList(pageSel.CurrentPage, pageSel.PageSize);
        }
        return dbset.Where(query).OrderByDescending(c => pageSel.OrderByKey).ToPagedList(pageSel.CurrentPage, pageSel.PageSize);
        
    }


以上是失败代码 想要的结果是正常返回值

QueryModel

------解决方案--------------------
反射吧。

return dbset.Where(query).OrderBy(c => key.GetValue(c,null)).ToPagedList(pageSel.CurrentPage, pageSel.PageSize);
------解决方案--------------------
yes ...i think dynamic linq is ok.
http://weblogs.asp.net/scottgu/archive/2008/01/07/dynamic-linq-part-1-using-the-linq-dynamic-query-library.aspx