user3125254
user3125254

Reputation: 219

Reverse Link Query

I am using asp.net 4.5.1 webform with EF codefirst; There is two class of Product and category; each product can have many categories. and each category can have many products. when I want select all the products in the selected categories by user, I use :

List<int> CatId = new List<int>(); 
// add all the selected category Id to the CatId list.   
_db.Categories.Where(p => CatId.Contains(p.CategoryID)).SelectMany(p => p.Products);

this code work goods. my question is that how can I write this query in the reverse view? Let me explain more, this code is selecting the categories that user selected then select all the products in those category.(from category view) but I want do this from Product View, it means first select products then check that product is in that category or not.

I know the result of both query is same. but I need to do this.

Upvotes: 0

Views: 78

Answers (1)

Sergey Berezovskiy
Sergey Berezovskiy

Reputation: 236318

If product has only one category:

_db.Products.Where(p => CatId.Contains(p.Category.CategoryID));

If product can have multiple categories:

_db.Products.Where(p => p.Categories.Any(c => CatId.Contains(c.CategoryID)));

Consider also renaming categories ids list to categoryIds to show that it is a collection of ids, not single id.

Upvotes: 1

Related Questions