Dapper passing dynamic param

c# dapper orm

Question

I am currently in the process of writing a wrapper for Dapper. This wrapper forces every query to be a stored procedure.

In my wrapper, I am calling Dapper like so (with the problem):

public IEnumerable<T> Select<T>(string storedProcName, dynamic param) {
    IEnumerable<T> results;

    using(var connection = new SqlConnection(_connectionString) {
        results = connection.Query<T>(storedProcName, param, commandType: CommandType.StoredProcedure);
    }

    return results;
}

When I try to pass "param" to the Query, it tells me "Cannot resolve symbol Query." When I remove the param pass, it works fine.

Can anyone point me in the right direction so that I can pass dynamic params (or something like it) on to Dapper?

Accepted Answer

You just need to change param to type object and when you call it you can use an anonymous type to pass in your params.

public IEnumerable<T> Select<T>(string storedProcName, object param) {
    IEnumerable<T> results;

    using(var connection = new SqlConnection(_connectionString) {
        results = connection.Query<T>(storedProcName, param, commandType: CommandType.StoredProcedure);
    }

    return results;
}

Then you would call it like this:

var results = query.Select<Entity>("spname", new { Id = 2, Something = "test" });

Expert Answer

You can probably just cast it away:

results = connection.Query<T>(storedProcName,
    (object)param, commandType: CommandType.StoredProcedure);

I'm re-doubting the wisdom of that dynamic; I know there was a reason, but I suspect it causes more harm than good. Frankly, dapper would work fine with object (the "reason" was an IDE issue, not a language issue).




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