实体框架跳过按组取

本文关键字:框架 实体 | 更新日期: 2023-09-27 18:04:22

当前正在"分页"一个表("Table1"),该表具有以下字段{Policy, Name, Amount, Date},并且在"Table1"中可以有多个策略记录,如下所示:

return context.Table1s.Orderby(i => i.Policy)
                      .Skip(endingRecord).Take(page)
                      .ToList();

如果我想首先按策略分组,然后跳过并采用不同的策略(基本上是尝试确保"页面"包含该页中包含的策略的所有记录),我该如何做?

我使用c#,实体框架,如果可能的话更喜欢"lambda"语法。

实体框架跳过按组取

return context.Table1s.GroupBy(i => i.Policy)
                      .Select(g => g.First())
                      .Orderby(i => i.Policy)
                      .Skip(endingRecord).Take(page)
                      .ToList();

生成如下SQL (LinqPad的Linq to SQL示例):

SELECT [t4].[test], [t4].[Name], [t4].[Policy], [t4].[Amount], [t4].[Date]
FROM (
    SELECT ROW_NUMBER() OVER (ORDER BY [t3].[Policy]) AS [ROW_NUMBER], [t3].[test], [t3].[Name], [t3].[Policy], [t3].[Amount], [t3].[Date]
    FROM (
        SELECT [t0].[Policy]
        FROM Table1s AS [t0]
        GROUP BY [t0].[Policy]
        ) AS [t1]
    OUTER APPLY (
        SELECT TOP (1) 1 AS [test], [t2].[Name], [t2].[Policy], [t2].[Amount], [t2].[Date]
        FROM Table1s AS [t2]
        WHERE (([t1].[Policy] IS NULL) AND ([t2].[Policy] IS NULL)) OR (([t1].[Policy] IS NOT NULL) AND ([t2].[Policy] IS NOT NULL) AND ([t1].[Policy] = [t2].[Policy]))
        ) AS [t3]
    ) AS [t4]
WHERE [t4].[ROW_NUMBER] BETWEEN @p0 + 1 AND @p0 + @p1
ORDER BY [t4].[ROW_NUMBER]

下面是我想要的结果

   return context.Tables1
                .Where(i =>
                    context.Tables1
                    .GroupBy(t => t.Policy)
                    .OrderBy(t => t.Key)
                    .Skip(previousRecordCount).Take(page)
                    .Select(t => t.Key)
                    .Contains(i.Policy))
                    .ToList();

您可以使用SkipWhileTakeWhile方法,但您需要将其分开如下:

var policyStart = context.Table1s.Orderby(i => i.Policy).ToList().SkipWhile(i => i.Policy == endingRecord.Policy);
var firstPolicy = policyStart.FirstOrDefault().Policy;
return policyStart.TakeWhile(i => i.Policy == firstPolicy).ToList();