Drizin/DapperQueryBuilder

Not able to use interpolation for column names and query operators

sushilnyk opened this issue · 3 comments

Hi
I am trying to parameterize the column names and query operator as I want to write some dynamic queries as given below

var searchQuery= cn.QueryBuilder($@"SELECT columnA
FROM table A

                                        /**where**/");

searchQuery.Where($" {q.field} {q.Operator} {q.Value}");

but above query doesnot execute .

but if I rewrite 2nd statement like below , the query executes

searchQuery.Where($" HairTypeEnum = {q.Value}");

Let me know if this is an issue

The major idea is that when you're adding interpolated parameters they are all converted to Dapper Parameters (SqlParameters). If you want to just pass raw strings, use :raw modifier:
searchQuery.Where($" {q.field:raw} {q.Operator:raw} {q.Value}");

In this case above, q.Value will be converted into a parameter (e.g. @p0), while the others will be passed as regular SQL statements.

Beware that when you pass something as raw you should ensure that the string is safe (if it's user input you should check/sanitize it before passing as raw)

Yeah I am checking whether those column names and operators are valid before adding them as parameters.
Is there any way I can write that way . I checked Dapper sql builder allows me to write this way but I wanted to use query builder as it provides more flexibility in writing dynamic AND/OR filters .

Thanks

:raw modifier is the only way of dynamically passing SQL statements.
Any other object passed using string interpolation is converted into @p SqlParameters.