0

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?

2
  • you could use something like github.com/TroyGoode/PagedList to do the paging etc for you btw Commented Apr 22, 2012 at 10:40
  • I saw that its a little complicated for what i want to do. Commented Apr 22, 2012 at 13:43

1 Answer 1

2

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);
Sign up to request clarification or add additional context in comments.

3 Comments

what about sorting? shouldn't it get sorted first and then paginated? how to sort it?
@cSharpper, You should OrderBy before Take and Skip to make the pagination get the page correctly, or at least keep the default order.
your code is correct but i finally wrote this code : var categoryModel = storeDB.Categories.Single(c => c.CategoryId == categoryId); var subCategoriesModel = storeDB.SubCategories.Where(c => c.CategoryId == categoryModel.CategoryId); var subcategoriesID = subCategoriesModel.Select(s => s.SubCategoryId).ToList(); var products = (from p in storeDB.Products where subcategoriesID.Contains(p.SubCategoryId) select p).OrderBy(p => p.ProductId).Skip((page - 1) * pageSize).Take(pageSize);

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.