Cornelis
Cornelis

Reputation: 1839

How to pass dynamic parameters in a method call

I am using dapper for getting data from the database and since database connections need to be disposed I put it in a using block. But I started to notice I saw a lot of the same usings and I thought it might be smart to write a wrapper function, something like this:

    protected IEnumerable<T> Query<T>(string query, dynamic param = null)
    {
        var connectionString = ConfigurationManager.ConnectionStrings["SomeString"].ConnectionString;

        using (var connection = new SqlConnection(connectionString))
        {
            return connection.Query<T>(query, param);
        }
    }

But this won't compile and I don't quite understand the error I get:

System.Data.SqlClient.SqlConnection' has no applicable method named 'Query' but appears to have an extension method by that name. Extension methods cannot be dynamically dispatched. Consider casting the dynamic arguments or calling the extension method without the extension method syntax

What am I doing wrong and what is the right way to pass dynamic parameters the way I am trying here?

Upvotes: 2

Views: 4932

Answers (1)

Ashley Medway
Ashley Medway

Reputation: 7301

use object instead of dynamic.

public IEnumerable<T> Query<T>(string query, object param) 
{
    var connectionString = ConfigurationManager.ConnectionStrings["SomeString"].ConnectionString;

    using(var connection = new SqlConnection(connectionString)) 
    {
        return connection.Query<T>(query, param);
    }
}

Upvotes: 4

Related Questions