简体   繁体   中英

Get top n records with top m of relative table in Entity Framework

I have a table Categories and Products . One category can have multiple products and I want to get TOP 5 products and TOP 3 categories for each product. I tried

entity.Categories.Include("Products").Take(3)

But output of this is 3 Categories and all products under them. I tried

entity.Categories.Take(5).Include("Products").Take(3)

But of course it won't work because Include can't be called in Take . So what could be the solution? Please suggest.

Finally I have solved it

var result = entity.Categories.Select
                         (
                            cats => new
                                {   
                                    cats.CategoryName,
                                    cats.Description,
                                    Products = cats.Products.Take(3)
                                }
                         ).Take(5);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM