动态linq似乎在GroupBy子句中不起作用

时间:2019-10-14 05:26:41

标签: c# entity-framework linq dynamic linq-to-sql

我有一个问题,我们将很多数据分组为所谓的阶段。前端希望在呈现数据之前按阶段显示此数据。阶段数是可变的。因此,最初,他们在绑定到网格控件之前会在每个阶段制作一个api,以对数据进行汇总。

当级数变得很高时,它会变得太慢。浏览器将对api请求进行排队,并且总体响应时间将非常长。更好-我们决定-将拥有一个可以处理分组和分页的api调用。也就是说,您可以说“ take = 30”,它会为您提供30个EACH阶段的记录,无论阶段多少。

所以后端的查询看起来像我下面的内容。问题在于,在进行跳过和获取之前,数据的排序位于动态字段上,这是数据的落脚之处。 Dynamic Linq似乎不起作用(尽管对于GroupBy调用之外的常规查询而言,它工作得很好),而且我也无法获得大量的扩展方法。它们都是您将在下面发现的错误的一些变体:(请记住,问题是它与linq to sql一起使用)

        TestEntities context = new TestEntities();

        List<TestTable1> result;

        // This works (Hard coding at design time)
        result = context.TestTable1.GroupBy(x => x.StageId)
            .SelectMany(x => x.OrderBy(y => y.StageId).Skip(1).Take(1)).ToList();

        // This works (using a hard coded function at design time)
        Func<TestTable1, int> orderByExpression = x => x.StageId;
        result = context.TestTable1.GroupBy(x => x.StageId)
            .SelectMany(x => x.OrderBy(orderByExpression).Skip(1).Take(1)).ToList();

        // This doesn't work. Dynamic linq            
        result = context.TestTable1.GroupBy(x => x.StageId)
            .SelectMany(x => x.AsQueryable().OrderBy("Name").Skip(1).Take(1)).ToList();

        // This doesn't work. Can't convert an object to a primitive type
        Func<TestTable1, object> orderByObjectExpression = x => x.StageId;
        result = context.TestTable1.GroupBy(x => x.StageId)
            .SelectMany(x => x.AsQueryable().OrderBy(orderByObjectExpression).Skip(1).Take(1)).ToList();

        // This doesn't work. Same as above
        Func<TestTable1, dynamic> orderByDynamicExpression = x => x.StageId;
        result = context.TestTable1.GroupBy(x => x.StageId)
            .SelectMany(x => x.AsQueryable().OrderBy(orderByObjectExpression).Skip(1).Take(1)).ToList();           

        Console.WriteLine(JsonConvert.SerializeObject(result));
        Console.ReadKey();

0 个答案:

没有答案