gpt4 book ai didi

c# - Dapper,避免 "The connectionstring property has not been initialized"错误

转载 作者:行者123 更新时间:2023-11-30 16:00:31 25 4
gpt4 key购买 nike

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

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

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 为空。

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

最佳答案

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;
}
}

关于c# - Dapper,避免 "The connectionstring property has not been initialized"错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39957001/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com