c# - 确保每次使用 Dapper 访问数据库时数据库连接打开和关闭

标签 c# sql sql-server database-connection dapper

这是我当前在我的存储库类之一中所做的事情:

private IDbConnection db = new SqlConnection(ConfigurationManager.ConnectionStrings["MyConnString"].ConnectionString);

public IEnumerable<Product> GetProducts(int categoryId = null, bool? active = null)
{
    StringBuilder sql = new StringBuilder();
    sql.AppendLine("SELECT * ");
    sql.AppendLine("FROM Product ");
    sql.AppendLine("WHERE @CategoryId IS NULL OR CategoryId = @CategoryId ");
    sql.AppendLine("  AND @Active IS NULL OR Active = @Active");

    return this.db.Query<Product>(sql.ToString(), new { CategoryId = categoryId, Active = active }).ToList();
}

我想做的一件事是将 IDbConnection 属性放入我的所有其他存储库继承的 BaseRepository 中。我该如何确保我的数据库连接在每个数据访问函数(如上面的示例)中正确打开和关闭?以下是我目前使用 Entity Framework 所做的事情(每个函数都有一个 using 语句,但现在我将 DAL 切换为使用纯 Dapper:

using (var context = new MyAppContext())
{
    var objList = (from p in context.Products
                   where (categoryId == null || p.CategoryId == categoryId) &&
                         (active == null || p.Active == active)
                   select p).ToList();

    return objList;
}

我在Dapper中注意到examples就像我所期望的那样,所有内容都包装在 using 语句中,但有时我看到他们将其函数包装在以下 using 中:

using (var connection = Program.GetClosedConnection())

GetClosedConnection()返回一个新的SqlConnection,但是两者有什么区别呢?

public static SqlConnection GetOpenConnection(bool mars = false)
{
    var cs = connectionString;
    if (mars)
    {
        SqlConnectionStringBuilder scsb = new SqlConnectionStringBuilder(cs);
        scsb.MultipleActiveResultSets = true;
        cs = scsb.ConnectionString;
    }
    var connection = new SqlConnection(cs);
    connection.Open();
    return connection;
}
public static SqlConnection GetClosedConnection()
{
    return new SqlConnection(connectionString);
}

最佳答案

我一直都是这么做的:

SqlConnection dbConnection;
using (dbConnection = new SqlConnection(connectionString))
{
    /* 
       Whatever Dapper stuff you want to do. Dapper will open the
       connection and the using will tear it down.
    */
}

至于你问题的第二部分,GetClosedConnection只需实例化 SqlConnection对象,而 GetOpenConnection实例化并打开 SqlConnection目的。您(或 Dapper)必须手动调用 Open()GetClosedConnection 返回的对象上.

关于c# - 确保每次使用 Dapper 访问数据库时数据库连接打开和关闭,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31013666/

相关文章:

sql - 使用 sp_executesql 时列名无效

c# - 控件上的鼠标按下时间最短

c# - 如何测试所有 ASP.NET Core Controllers 的依赖注入(inject)是否有效?

php - 最小值和最大值之间 mysqli

sql-server - 请确认: SYSDATETIME() is slower than GETDATE() in WHERE clause

sql-server - 使用子查询累计和后的 Top 9 Distinct 记录

sql-server - SQL 从动态 SQL 写入临时表

c# - 创建一个随机名称生成器。我该如何做到这一点?

c# - 使用自定义模式重定向到外部 URL

sql - 如何从列中删除第 i 个项目?