Dapper 异常 - 当“buffered”为“false”时“ConnectionString 属性尚未初始化”

lij*_*alo 5 c# connection-string sqlexception dapper

我正在尝试 Dapper,偶然发现了这个异常:

System.InvalidOperationException: The ConnectionString property has not been initialized.
...
Run Code Online (Sandbox Code Playgroud)

这是代码:

public IEnumerable<T> GetAll<T>(string sql, DynamicParameters parameters, string connectionString, CommandType commandType = CommandType.StoredProcedure)
{
    using IDbConnection db = new SqlConnection(connectionString);
    var result = db.Query<T>(sql, parameters, commandType: commandType, commandTimeout: COMMAND_TIMEOUT, buffered: false);
    return result;
}
Run Code Online (Sandbox Code Playgroud)

当我删除buffered参数时,一切正常。

var result = db.Query<T>(sql, parameters, commandType: commandType, commandTimeout: COMMAND_TIMEOUT);
Run Code Online (Sandbox Code Playgroud)

Mar*_*ell 3

我怀疑这里真正的问题是您正在返回一个开放的可查询,这意味着您将离开块的范围并处置仍在使用的using连接。这里真正的问题是一个对象处理得太早,但它以一种不寻常的方式表现出来。

基本上,在处理完需要连接的数据之前,您不需要释放连接。一种懒惰的方法是:

using IDbConnection db = new SqlConnection(connectionString);
foreach (var row in db.Query<T>(sql, parameters, commandType: commandType, commandTimeout: COMMAND_TIMEOUT, buffered: false)
{
    yield return row;
}
Run Code Online (Sandbox Code Playgroud)

仅当不缓冲数据时才会发生这种情况,因为缓冲意味着“在返回给调用者之前获取所有数据”,而不是返回打开的查询。通过切换到“迭代器块”(通过yield return),范围using会扩展,直到最后一个数据被消耗(或者循环以其他方式退出)。