作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
当我尝试调用两种方法并且每个方法都在数据库中进行查询时,我的应用程序出现了问题。这些方法都使用了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/
我是一名优秀的程序员,十分优秀!