我想返回按特定属性分组的某个实体的列表,按时间戳降序排序并分页(使用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()(尽管是Descending),我在Skip()之前调用它!我错过了什么?
答案 0 :(得分: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);
答案 1 :(得分: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);