Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

LINQ many to many hell - querying where CONTAINS ALL

I have a many to many relationship as follows:

Products ProductID Description

ProductFeatures ProductFeatureID ProductID FeatureID

Features FeatureID Description

Any Product can have many Features.

I then come along with an iQueryable called "SearchFeatures" which contains two particular Feature objects that I want to search on.

I want to find the Products which have ALL of these Features!

E.g. something like this would be nice:

return db.Products.Where(x => x.Features.ContainsAll(SearchFeatures));

What is the cleanest way to achieve this using LINQ?

Many thanks.

like image 855
Aaron Avatar asked Jan 22 '23 17:01

Aaron


2 Answers

IQueryable<Products> products = db.Products;
foreach (var feature in SearchFeatures)
{
    Feature tmpFeature = feature;
    products = products
        .Where(x=>x.ProductFeatures.Any(y=>y.FeatureID == tmpFeature.FeatureID));
}
like image 173
Francisco Avatar answered Apr 29 '23 04:04

Francisco


from item in db.Products
where item.ProductFeatures.Where(x=>featIdList.Contains(x.FeatureId)).Count() == featIdList.Count
select item

This should do it. featIdList is a list of the feature ids that you're looking for

like image 38
Mike Avatar answered Apr 29 '23 02:04

Mike