entity framework: conditional filter
c#-4.0, entity-framework
Solution
You can include conditional parameter this way:
return Customers.Where(
customer =>
customer.Name == Name &&
(Age == "All" || customer.Age == Age) &&
(Income == "All" || customer.Income == Income) &&
(Country == "All" || customer.Country == Country)
).ToList();
If some condition is true (e.g. country is equal to `All`), then all parameter condition becomes true, and this parameter does not filter result.
Problem
Let's say I have Customers table and I want to filter it by the following: - Country: All, US, UK, Canada - Income: All, low, high, medium - Age:All, teenager, adult, senior if I had to build an SQL string for this filter, it would be something like this: ``` if (Country != "All") sql += "country = " + Country if (Income != "All") sql += "and income = " + Income if (Age != "All") sql += "and age = " + Age; ``` So, basically, the user can filter by some, but not necessary all fields. How do you do this using Entity Framework ? Thanks !