【发布时间】:2013-03-01 17:31:34
【问题描述】:
编译错误
“System.Data.SqlClient.SqlConnection”没有名为“Query”的适用方法,但似乎具有该名称的扩展方法。扩展方法不能动态调度。考虑强制转换动态参数或调用扩展方法而不使用扩展方法语法。
现在,我知道如何解决该问题,但我正试图更好地了解错误本身。我正在构建利用 Dapper 的课程。最后,我将提供更多自定义功能,以使我们的数据访问类型更加简化。特别是在跟踪和东西方面的建设。但是,现在就这么简单:
public class Connection : IDisposable
{
private SqlConnection _connection;
public Connection()
{
var connectionString = Convert.ToString(ConfigurationManager.ConnectionStrings["ConnectionString"]);
_connection = new SqlConnection(connectionString);
_connection.Open();
}
public void Dispose()
{
_connection.Close();
_connection.Dispose();
}
public IEnumerable<dynamic> Query(string sql, dynamic param = null, IDbTransaction transaction = null, bool buffered = true, int? commandTimeout = null, CommandType? commandType = null)
{
// this one works fine, without compile error, so I understand how to
// workaround the error
return Dapper.SqlMapper.Query(_connection, sql, param, transaction, buffered, commandTimeout, commandType);
}
public IEnumerable<T> Query<T>(string sql, dynamic param = null, IDbTransaction transaction = null, bool buffered = true, int? commandTimeout = null, CommandType? commandType = null)
{
// this one is failing with the error
return (IEnumerable<T>)_connection.Query(sql, param, transaction, buffered, commandTimeout, commandType);
}
}
但有趣的是,如果我只是发表这样的声明:
_connection.Query("SELECT * FROM SomeTable");
它编译得很好。
那么,有人可以帮我理解为什么在其他方法中利用相同的重载会因该错误而失败吗?
【问题讨论】:
-
@pst,很公平,从技术上讲,它不是抛出的。
-
为什么需要动态参数,而不是对象参数?您没有对其进行任何操作或方法调用。你是吗?
标签: c# .net compiler-errors extension-methods dapper