4

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();

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

2 Comments

How would you add aParam, bParam dynamically in the second snippet? Is it possible to replace new { aParam, bParam } with an ExpandoObject? I don't want to hard-code aParam, bParam. I want to add them via a loop. It seems like Query<Equipment>() does not support an ExpandoObject as its second argument though.
@kkuilla you can use DynamicParameters, or frankly you can just pass both in (dapper will ignore any that obviously aren't used)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.