I have a customer entity whose records I want to be able to search by multiple arbitrary attributes.
E.g.:
Dictionary<string, string> searchList = new Dictionary<string, string>();
searchList.Add("LastName", "Foo");
searchList.Add("FirstName", "Bar");
I could of course write something along these lines:
foreach (KeyValuePair<string, string> kv in searchList)
{
switch (kv.Key)
{
case "FirstName" :
List<Customer> someResultPart = this._dbSet.Where(customer => customer.FirstName == kv.Value).ToList();
break;
case "LastName" :
// etc.
}
}
// Do intersection of all result parts ...
Aside from the fact that querying n times and intersecting later on is obviously fugly, I would much rather not have that switch statement in there (since it would force me to change it every single time anything in the Customer class changes.
Is there any way to:
- “dynamically” build the query based on the
searchListdictionary, thereby eliminating the need for theswitchconstruct? - “concatenate” the various conditions into a single db query?
You can use Dynamic LINQ
Or this way:
I’d even constructed full search predicate like this: