33

编译错误

“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");

它编译得很好。

那么,有人可以帮我理解为什么在其他方法中利用相同的重载会因该错误而失败吗?

4

2 回答 2

46

那么,有人可以帮我理解为什么在其他方法中利用相同的重载会因该错误而失败吗?

正是因为您使用动态值 ( param) 作为参数之一。这意味着它将使用动态调度......但扩展方法不支持动态调度。

解决方案很简单:直接调用静态方法:

return SqlMapper.Query(_connection, sql, param, transaction,
                       buffered, commandTimeout, commandType);

(这是假设您确实需要paramtype dynamic,当然...如评论中所述,您可能只需将其更改为object.)

于 2013-03-13T16:40:36.637 回答
1

同一问题的另一个解决方案是将类型转换应用于动态值。

我遇到了同样的编译错误:

Url.Asset( "path/" + article.logo );

通过这样做解决了:

Url.Asset( "path/" + (string) article.logo );

注意:动态值是众所周知的字符串,在这种情况下;存在的字符串连接强化了一个事实。

于 2015-12-01T16:03:47.257 回答