通用命令LINQ

时间:2014-02-08 07:53:38

标签: linq generics sql-order-by

我有一个通用的存储库方法来启用服务器端分页:

public virtual IEnumerable<T> GetList(out int totalPages, Expression<Func<T, bool>> filter = null,
                                            Expression<Func<T, object>> orderby = null,
                                            bool ascending = true,
                                            string includeProperties = "",
                                            int pageSize = 10, int pageNumber = 1)
    {
        IQueryable<T> query = c.Set<T>();
        if (filter != null)
        {
            query = query.Where(filter);
        }

        query = includeProperties.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries).Aggregate(query, (current, includeProp) => current.Include(includeProp));

        if (orderby != null)
        {
            query = @ascending ? query.OrderBy(@orderby) : query.OrderByDescending(@orderby);
        }
        else
        {
            query = @ascending ? query.OrderBy(o => o.Id) : query.OrderByDescending(o => o.Id);
        }

        //totalPages = (int) Math.Ceiling((double)(Queryable.Count(query) / pageSize));
        totalPages = 1;

        if (pageSize > 0)
        {
            var skip = 0;
            var take = pageSize;
            if (pageNumber > 1)
            {
                skip = (pageNumber - 1) * pageSize;
                take = pageSize + skip;
            }
            query = query.Take(take);
            query = query.Skip(skip);
        }
        return query.ToList();
    }

T是我的实体继承的基类 我从我的服务中调用此存储库方法。我从我的控制器调用我的服务。 现在从我的控制器如何创建我的orderby表达式,以便我可以传递任何列名?

到目前为止我已尝试过(在stackoverflow上找到):

           var _OrderByProperty = typeof(Year).GetProperty("Id");
        var _OrderByParameter = Expression.Parameter(typeof(Year), "x");            
        var _OrderByBody = Expression.Property(_OrderByParameter, _OrderByProperty.Name);
        var _OrderByConverted = Expression.Convert(_OrderByBody, typeof(Object));
        var _OrderByLambda = Expression.Lambda<Func<Year, object>>
            (_OrderByConverted, _OrderByParameter);           

        var list = s.GetList(orderby: _OrderByLambda, totalPages: out totalPages, pageNumber: pageNumber, pageSize: pageSize, ascending: isAsc);

我收到了错误

无法将类型'System.Int32'强制转换为'System.Object'。 LINQ to Entities仅支持转换EDM原语或枚举类型。

0 个答案:

没有答案