Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Entity Framework skip take by group by

Tags:

c#

linq

group-by

I a currently "paging" through a table ("Table1") that has the following fields { Policy, Name, Amount, Date} and there can be mulitple records in "Table1" for a policy, like the following:

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

How would I do this if I wanted to first group by Policy and then skip and take on the distinct policies (basically trying to ensure that a "page" contains all the records for the policies included in the page)?

I'm using C#, entity framework and prefer the "lambda" syntax if possible.

like image 259
AWeim Avatar asked Mar 15 '13 17:03

AWeim


2 Answers

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

That generates SQL like this (sample from LinqPad for 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]
like image 111
Sergey Berezovskiy Avatar answered Nov 20 '22 14:11

Sergey Berezovskiy


The following gave me the desired results

   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();
like image 40
AWeim Avatar answered Nov 20 '22 13:11

AWeim