Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dapper passing dynamic param

Tags:

c#

orm

dapper

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?

like image 860
Sean Avatar asked May 25 '26 07:05

Sean


2 Answers

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" });
like image 51
Kevin Holditch Avatar answered May 27 '26 21:05

Kevin Holditch


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).

like image 34
Marc Gravell Avatar answered May 27 '26 22:05

Marc Gravell