Reputation: 3212
I have categories and subcategories. Each subcategory has some products. e.g programming category has | C# , java , basic subcategories | where c# has c# 3 , c# 3.5 products | java has java ee , java me and so on
I want to select 10 products from categories using linq to EF.
The problem is that I don't want to load all products from the database and then sort them and then select 10 of them.
I want a solution which i can just take 10 products from database without transferring all products from the database back to web server.
I know that EF is greedy and would take only 10 products and skip some. but in my case which i have categories and subcategories so I think I should first select all products from different subcategories belonging to a category and append them to a list which cause bringing all products to server and then select 10 of them.
What is the best practice so that i don't have to transfer all products to server?
Upvotes: 0
Views: 605
Reputation: 79929
You can do this in one query:
var pagedProducts = _db.Categories.Join(
_db.Products,
c => c.CategoryId,
p => p.CategoryId,
(Category, Products) =>
new
{
CategoryType = Category,
ItsProducts = Products
})
.OrderBy(g => g.Category.Name)
.Skip((CurrentPage - 1) * pageSize)
.Take(pageSize);
Upvotes: 2