Reputation: 15
I have two classes that form a many to many relationship.
public class Product
{
public int ID { get; set; }
public virtual ICollection<Category> Categories{ get; set; }
}
public class Category
{
public int ID { get; set; }
public virtual ICollection<Product> Products{ get; set; }
}
I need to select all the products which are contain in certain category. For example all the product in category with ID equal to 1, Or all the products in the categories with ID 1 and 3. How can I write this query in Linq?
Note: I want Use this as filtering technique. I have this code:
public IQueryable<Product> GVProducts_GetData(string Sort)
{
var query = _db.Products.AsQueryable();
//Here I want filter my data
if (Sort == "1")
{
query = (here should select all the product which are in category 1)
}
else if (Sort == "2")
{
query = (here should select all the product which are in category 2)
}
return query;
}
Upvotes: 0
Views: 536
Reputation: 7836
Create method:
public IEnumerable<Product> GetProducts(params int[] selectCategory )
{
return repository.Query<Category>
(p => selectCategory.Contains(p.ID)).SelectMany(p => p.Products).ToList()
}
example of use:
var product = GetProducts(1,3,5);
where 1,3,5 sought category
Upvotes: 1
Reputation: 1868
DbContext.Category.Where(c => c.ID == 1)
.Include(c => c.Products).Select(x => x.Products).ToList();
Could be something like this. Make sure to use Include.
Upvotes: 2