Dynamic Parameterized query with dapper

c# dapper oracle sql

Question

I want to write a query with a dynamic list of parameters (depending on parameter is set or not). I want to execute the query on an oracle database using dapper.

Sample code:

        var sqlParams = new List<object>();
        var sqlBuilder = new StringBuilder();
        sqlBuilder.Append("SELECT * FROM EXAMPLE WHERE 1 = 1 ");

        if (!string.IsNullOrEmpty(aParam))
        {
            sqlBuilder.Append(" AND A LIKE ?");
        }

        if (!string.IsNullOrEmpty(bParam))
        {
            sqlBuilder.Append(" AND B LIKE ? ");
        }

        var sql = sqlBuilder.ToString();

        return this.Connection.Query<Equipment>(
            sql,
            new { aParam, bParam }   // ??
            ).ToList();

Accepted Answer

Dapper only really works with named parameters. I seem to recall that in oracle they are colon-prefixed, so:

if (!string.IsNullOrEmpty(aParam))
{
    sqlBuilder.Append(" AND A LIKE :aParam");
}

if (!string.IsNullOrEmpty(bParam))
{
    sqlBuilder.Append(" AND B LIKE :bParam");
}

Now your existing code here:

return this.Connection.Query<Equipment>(
    sql,
    new { aParam, bParam }
    ).ToList();

should work. Dapper uses the names of the members of the anonymous type as parameter names. It additionally includes some very basic code to check whether any given member does not exist in the sql, so if your sql only mentions :bParam, it won't actually add the aParam value as a parameter.

In more complicated scenarios, there is also a DynamicParameters object you can use, that functions more like a dictionary - but you don't need that here.




Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Is this KB legal? Yes, learn why
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Is this KB legal? Yes, learn why