title: How to select top N rows for each group in a Entity Framework GroupBy with EF 3.1
body: <p>I need to get top 10 rows for each group in a table with entity framework.
  Based on other solution on SO, I tried 2 things:</p>
  
  <pre><code>var sendDocuments = await context.Set&lt;DbDocument&gt;
      .Where(t =&gt; partnerIds.Contains(t.SenderId))
      .GroupBy(t =&gt; t.SenderId)
      .Select(t =&gt; new
      {
          t.Key,
          Documents = t.OrderByDescending(t2 =&gt; t2.InsertedDateTime).Take(10)
      })                
      .ToArrayAsync();
  </code></pre>
  
  <p>error:</p>
  
  <pre><code>System.InvalidOperationException: 'The LINQ expression
  '(GroupByShaperExpression: KeySelector: (d.SenderId), 
  ElementSelector:(EntityShaperExpression: 
      EntityType: DbDocument
      ValueBufferExpression: 
          (ProjectionBindingExpression: EmptyProjectionMember)
      IsNullable: False ) )
      .OrderByDescending(t2 =&gt; t2.InsertedDateTime)' could not be translated. Either rewrite the query in a form that can be translated,
  &gt; or switch to client evaluation explicitly by inserting a call to
  &gt; either AsEnumerable(), AsAsyncEnumerable(), ToList(), or
  &gt; ToListAsync().
  </code></pre>
  
  <p>and</p>
  
  <pre><code>var sendDocuments2 = await context.Set&lt;DbDocument&gt;
      .Where(t =&gt; partnerIds.Contains(t.SenderId))
      .GroupBy(t =&gt; t.SenderId)
      .SelectMany(t =&gt; t.OrderByDescending(t2 =&gt; t2.InsertedDateTime).Take(10))
      .ToArrayAsync();
  </code></pre>
  
  <p>error:</p>
  
  <blockquote>
    <p>System.InvalidOperationException: 'Processing of the LINQ expression
    't => t
        .OrderByDescending(t2 => t2.InsertedDateTime)
        .AsQueryable()
        .Take(10)' by 'NavigationExpandingExpressionVisitor' failed. This may indicate either a bug or a limitation in EF Core.</p>
  </blockquote>
  
  <p>Any other idea?</p>