I am looking for some tips and tricks how to build dynamic queries. I am having an application which lets the user search 10 fields in the database table. Depending on which fields in the UI are filled with a value the query should search in an additional field in the DB.
Currently I am trying to build the query using StringBuilder and adding the where clause but I really don't like this and I am wondering if there is a better way to do this, for example with LINQ if possible.
Maybe someone can bring up ideas or better some example code. Thanks and have a nice day!
With LINQ it is pretty trivial:
Each successive
Where
composes the query with more filters; exactly what you want.With raw TSQL,
StringBuilder
isn't unreasonable; just make sure that you fully parameterize it. This might mean adding parameters in each term; for example: