How to select top N rows for each group in a Entity Framework GroupBy with EF 3.1

前端 未结 2 1462
悲&欢浪女
悲&欢浪女 2020-12-02 00:16

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:

var sendDocuments = await context         


        
相关标签:
2条回答
  • 2020-12-02 01:08

    This is a common problem, unfortunately not supported by EF Core 3.0/3.1 query translator specifically for GroupBy.

    The workaround is to do the groping manually by correlating 2 subqueries - one for keys and one for corresponding data.

    Applying it to your examples would be something like this.

    If you need (key, items) pairs:

    var query = context.Set<DbDocument>()
        .Where(t => partnerIds.Contains(t.SenderId))
        .Select(t => t.SenderId).Distinct() // <--
        .Select(key => new
        {
            Key = key,
            Documents = 
                context.Set<DbDocument>().Where(t => t.SenderId == key) // <--
                     .OrderByDescending(t => t.InsertedDateTime).Take(10)
                     .ToList() // <--
        });
    

    If you need just flat result set containing top N items per key:

    var query = context.Set<DbDocument>()
        .Where(t => partnerIds.Contains(t.SenderId))
        .Select(t => t.SenderId).Distinct() // <--
        .SelectMany(key => context.Set<DbDocument>().Where(t => t.SenderId == key) // <--
            .OrderByDescending(t => t.InsertedDateTime).Take(10)
        );
    
    0 讨论(0)
  • 2020-12-02 01:10

    maybe try a different approach?

     var partnersList = context.partnerIds.Where(x=> "your where clause here").Take(10).Tolist()
    
    0 讨论(0)
提交回复
热议问题