【问题标题】:Dapper, avoiding "The connectionstring property has not been initialized" errorDapper,避免“连接字符串属性尚未初始化”错误
【发布时间】:2016-10-10 21:26:35
【问题描述】:

当我尝试调用两个方法并且每个方法都在数据库中执行查询时,我的应用程序出现问题。 这些方法都是使用using语句,所以在使用后会关闭连接。

我创建了一个 DapperContext,并使用简单的注入器通过构造函数进行初始化:

public DapperContext(int idPortal)
{
    _connectionString = GetERPConnectionString(idPortal);
}

为了打开连接并在数据库中进行查询,我创建了如下属性:

public IDbConnection DapperConnection
{
    get
    {
        if (_connection == null)
        {
            _connection = new SqlConnection(_connectionString);                    
        }

        if (_connection.State != ConnectionState.Open)
        {
            _connection.Open();
        }

        return _connection;
    }
}

这个 DapperContext 有一个 Dispose 方法,它会关闭连接:

public void Dispose()
{
    if (_connection != null && _connection.State == ConnectionState.Open)
    {
        _connection.Close();
    }

    GC.SuppressFinalize(this);
}

在 Repository 类中,有一个方法将执行 2 个不同的 Sql,这 2 个 sql 分别在其方法中指定。 基本上,每个都是这样初始化的:

using (IDbConnection conexao = dapperContext.DapperConnection)
{
... runs a query
}

当我调用第一个方法时,查询运行良好,但是当调用第二个方法时,在 DapperConnection 属性中,_connection.Open() 中发生错误,因为 _connectionString 为空。

避免此错误的最佳方法是什么?我知道由于 Dispose 方法,connectionString 正在丢失,但是由于我使用 SimpleInjector 创建我的实例并且这是通过请求完成的,因此我只会在另一个请求中再次拥有此 connectionString。

【问题讨论】:

    标签: c# asp.net-mvc dapper


    【解决方案1】:
    using (IDbConnection conexao = dapperContext.DapperConnection)
    {
    }
    // -> conexao.Dispose() called on bound out, and _connection.Close(); is closed. 
    

    它的“_connection”关闭连接状态的结果,没有重复使用。所以,如果你想让这段代码正常工作,那么 Dispose 方法应该如下所示:

    public void Dispose()
    {
        if (_connection != null && _connection.State == ConnectionState.Open)
        {
            _connection.Close();
            _connection = null;
        }
    }
    

    【讨论】:

    • 嘿 Sergey,我是在 Dispose 方法中执行此操作的,所以至少 _connectionString 不再为空,所以我能够再次创建 _connection 而没有错误。
    猜你喜欢
    • 1970-01-01
    • 2017-09-14
    • 1970-01-01
    • 1970-01-01
    • 2013-08-03
    • 1970-01-01
    • 2020-02-20
    • 2017-10-10
    相关资源
    最近更新 更多