Reputation: 1839
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
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