排序不适用于动态列

时间:2011-06-10 10:53:31

标签: asp.net asp.net-mvc

我有一个通用函数,如:

public TabMasterListViewModel GetTabMasterList(string OrderByColumn, string OrderType, int PageSize, int CurrentPage)
        {
            try
            {
                if ((CurrentPage == 0) || (PageSize == 0))
                    return null;

                IQueryable<TabMaster> query = _tabmasterRepository.GetQueryable();
                TabMasterListViewModel model = new TabMasterListViewModel();
                model.TotalItemCount = query.Count();
                if (model.TotalItemCount == 0)
                    return null;
                model.TotalPageCount = (int)Math.Ceiling((double)model.TotalItemCount / (double)PageSize);
                if (model.TotalPageCount != 1)
                {
                    if (OrderType.ToUpper() == "ASC")
                        query = query.OrderBy(x => x.colID).Skip((CurrentPage - 1) * PageSize).Take(PageSize);
                    else
                        query = query.OrderByDescending(x => x.colID).Skip((CurrentPage - 1) * PageSize).Take(PageSize);
                }
                model.ThisPageItemCount = query.Count();
                model.TabMasterList = new List<TabMasterViewModel>();
                AutoMapper.Mapper.CreateMap<TabMaster, TabMasterViewModel>()
                    .ForMember(dest => dest.colID, opt => opt.MapFrom(src => src.colID));
                model.TabMasterList = AutoMapper.Mapper.Map(query.ToList(), model.TabMasterList);

                return model;
            }
            catch (System.Exception e)
            {
                this.LogError("Error getting the TabMaster list", e);
                return null;
            }
        }

如果我使用以下行

query = query.OrderBy(x => x.colID).Skip((CurrentPage - 1) * PageSize).Take(PageSize);

然后排序完成工作方面。

如果我在下一行中使用 OrderByColumn ,则排序不起作用。

 if (OrderType.ToUpper() == "ASC")
                        query = query.OrderBy(x => OrderByColumn).Skip((CurrentPage - 1) * PageSize).Take(PageSize);
                    else
                        query = query.OrderByDescending(x => OrderByColumn).Skip((CurrentPage - 1) * PageSize).Take(PageSize);

请建议我缺少什么? 谢谢,

3 个答案:

答案 0 :(得分:1)

这是同样的优秀解决方案

http://landman-code.blogspot.com/2008/11/linq-to-entities-string-based-dynamic.html

非常感谢 Davy Landman 提供出色的解决方案。

答案 1 :(得分:0)

您可以尝试dynamic LINQ。它更适合您尝试实现的动态查询类型。

答案 2 :(得分:0)

尝试使用反射来动态获取OrderByColumn

query = query.OrderBy(x => typeof(x).GetProperty(OrderByColumn)).Skip((CurrentPage - 1) * PageSize).Take(PageSize);