After many hours of googling and searching stackoverflow, I desperately need your help concerning an issue with Linq.
Imagine two tables:
Table A : Products
ID(int) | ProductName(varchar(50))
1___________|_______________A
2___________|_______________B
3___________|_______________C
...
Table B : ProductFeatures
ProductID(int) | FeatureID(int) | FeatureValue(smallint)
1_____________________|_________1_____________________|____________1
1_____________________|_________2_____________________|____________1
1_____________________|_________3_____________________|____________0
2_____________________|_________1_____________________|____________0
2_____________________|_________2_____________________|____________1
3_____________________|_________1_____________________|____________1
3_____________________|_________2_____________________|____________1
...
E.g.
FeatureID = 1 => "has WiFi"
FeatureValue 1 = Yes / 0 = No.
Table C: I also have a Feature description table
FeatureID int,
FeatureName varchar(50)
In my ASP application, I have a panel that contains controls like checkboxes/dropdownlists and allows the user to filter the list of Products.
So, if someone selects the ‘Laptops’ category, the page will display the list of laptops and furthermore he can click filters like “with WiFi” checkbox etc in order to narrow down the results.
My problem:
First, the Filter controls populate a List which contains the FeatureIDs that were requested:
List<int> filters=getFilterPanelList();
How can I Select all the Products from the Products table WHERE the Product’s features will contain at least the filters List? (in SQL or Linq script).
For example: if the controls produce the list (1,3) then the Linq query will return only the product 1 because it contains at least the 1 and 3 FeatureIDs.
I found something like the bellow SQL query but the ‘IN’ operator (or the ‘Contains’ function in Linq) returns all the products that contains FeatureID 1 or FeatureID 3 but not both of them:
SELECT ProductID
FROM
Products P
JOIN ProductFeatures PF ON PF.ProductID = P.ID
WHERE
PF.ProductID IN
SELECT ProductID
FROM
ProductFeatures
WHERE
FeatureID IN @FilterList)"
In Linq:
I assumed one product has not more then one feature of the same type.