I want to implement Advanced Search in my ASP.NET MVC Application, where user can select 1 or more criteria for the product search.
Let's say I have these criterias: Color, Size, Price Range.
This is as far as I get till now
ProductSizeList = db.ProductSizes.Where(ProductSize =>
(string.IsNullOrEmpty(ProductColorId) || ProductSize.Product.ProductColors.Where(a => a.ColorID == IntColorId).Any())
).GroupBy(x => x.ProductID).Select(Grouped => Grouped.FirstOrDefault()).ToList();
I have a many-to-many relationship between Product and Color tables, and ProductColor is the one linking them. Same thing with Product, ProductSize, Size tables.
The code is working perfectly with the Size, and Price Range. The problem with the Color, because .Any() returns when it finds the first Product. If There is more than one Product, it only returns the first one.
So, I want to know if there is another method, or another way to be able to get all products with the specified color.
I searched a lot, and know that I can build Where Clause Dynamically, but I think it would be too much work for my requirements. If there is a simple fix for this I would be more than happy.
Edit
I removed the working-as-wanted code as suggested by @Jeroen, and left the one I want to fix.
Solved
I fixed it, thanks to combining @jason and @Marlon answers. I'll put the solution in a separate answer. I just want to understand 2 points:
- Why it only worked Correctly when I based my query on Product?
- Why `.Distinct()` didn't do any thing, and I got duplicated products.