使用字符串的动态IQueryable顺序

时间:2012-11-06 13:36:34

标签: c# .net dynamic expression iqueryable

  

可能重复:
  Dynamic LINQ OrderBy

我正在尝试为Iqueryable创建动态排序 下面你可以看到我正在关注我在stackoverflow中看到的一些例子。

 var query = dalSession.Query<T>();
            var res = (from x in query orderby Extensions.Sort<T>(query, "FirstName") select x).Skip((paging.CurrentPageRecord)).Take(paging.PageSize);


public static class Extensions
{
    public static IQueryable<T> Sort<T>(this IQueryable<T> query,
                                             string sortField)
    {
        return query.OrderByDescending(s => s.GetType()
                                             .GetProperty(sortField));

    }
} 

这是我得到的例外:

  

System.Linq.IQueryable 1[Partners.BusinessObjects.Affiliate] Sort[Affiliate](System.Linq.IQueryable 1 [Partners.BusinessObjects.Affiliate],System.String)

Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code. 

Exception Details: System.NotSupportedException: System.Linq.IQueryable`1[Partners.BusinessObjects.Affiliate] Sort[Affiliate](System.Linq.IQueryable`1[Partners.BusinessObjects.Affiliate], System.String)

2 个答案:

答案 0 :(得分:2)

问题在于: -

s => s.GetType().GetProperty(sortField)

当您尝试访问IQueryable的结果集时,它会被转换为SQL并且查询将针对您的数据库运行(而不是在内存中运行)。问题是显然你的数据库对你的类型一无所知,不能调用它们上的任何方法,当然也不能对它们进行任何反射。

您需要构建自己的表达式树,并将其转换为SQL。表达式API非常复杂,如果你想真正得到它,你需要做很多阅读。 Here's a good starting point on creating dynamic queries using the expression API for you

值得庆幸的是,您的具体情况相当简单,并且有一些例子hereherehere,但我确实建议做一些阅读它以了解发生了什么。如果你只是复制粘贴,那么你或其他人最终将不得不维护它并且度过一段非常悲伤的时光。

答案 1 :(得分:-1)

Iain是对的,你的iqueryable只在真正需要时开始提取数据。您可以通过简单的技巧long dummy = query.Count();来强制加载。这不是完整的解决方案,您希望避免构建查询树的复杂性,因此如果集合不是非常大,只需将其转换为某种可排序类型。