7

我想返回按某个属性分组的某个实体的列表,按时间戳降序排列并分页(使用 Skip 和 Take)。我得到的是这样的:

container.CoinMessageSet.Where(
                c => c.MessageState != MessageStateType.Closed &&
                     (c.DonorOperator.OperatorCode.Equals("opcode") ||
                      c.RecipientOperator.OperatorCode.Equals("opcode"))
                ).OrderByDescending(c => c.TimeStamp)
                 .GroupBy(c => c.Reference).Skip(x).Take(100);

执行后我得到了异常:

The method 'Skip' is only supported for sorted input in LINQ to Entities. 
The method 'OrderBy' must be called before the method 'Skip'.

...我调用了 OrderBy()(尽管是降序),我在 Skip() 之前调用了它!我错过了什么?

4

2 回答 2

7

您还没有订购组;您需要先执行此操作,然后才能分页。例如:

.GroupBy(c => c.Reference).OrderBy(grp => grp.Key).Skip(x).Take(100);

OrderByDescending(如果您希望组以相反的顺序也可以替换)

另外:由于您正在分组,因此原始数据中的顺序在很大程度上没有意义;您可能可以删除OrderByDescending(c => c.TimeStamp).

所以最终结果:

var query = container.CoinMessageSet.Where(
            c => c.MessageState != MessageStateType.Closed &&
                 (c.DonorOperator.OperatorCode.Equals("opcode") ||
                  c.RecipientOperator.OperatorCode.Equals("opcode"))
            ).GroupBy(c => c.Reference).OrderBy(grp => grp.Key)
             .Skip(x).Take(100);

或者可能:

var query = (from c in container.CoinMessageSet
             where c.MessageState != MessageStateType.Closed &&
                  (c.DonorOperator.OperatorCode == "opcode" ||
                   c.RecipientOperator.OperatorCode == "opcode")
             group c by c.Reference into grp
             orderby grp.Key
             select grp).Skip(x).Take(100);
于 2013-01-08T11:31:51.357 回答
2

这很可能是GroupBy因为OrderByDescending.

我想你可以试试:

container.CoinMessageSet.Where(
                c => c.MessageState != MessageStateType.Closed &&
                     (c.DonorOperator.OperatorCode.Equals("opcode") ||
                      c.RecipientOperator.OperatorCode.Equals("opcode"))
                ).OrderByDescending(c => c.TimeStamp)
                 .GroupBy(c => c.Reference).OrderByDescending(c = > c.Key).Skip(x).Take(100);
于 2013-01-08T11:32:03.563 回答