我想返回由某个属性分组的某个实体的列表,按时间戳降序排序并进行分页(使用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()之前调用了它!我错过了什么?
您没有对分组进行排序;你需要这样做,然后才能呼出。例如:
.GroupBy(c => c.Reference).OrderBy(grp => grp.Key).Skip(x).Take(100);
(如果您希望组的顺序相反,也可以替换OrderByDescending
)
Also:因为你在分组,原始数据中的顺序在很大程度上是没有意义的;你可以把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);
很可能是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);