确保在调用每个repo函数后始终关闭SQL数据库连接

时间:2017-07-02 16:39:20

标签: c# sql-server repository dapper idisposable

我试图弄清楚我是否需​​要在每个存储库函数中使用using语句,以确保在每批数据库调用后关闭连接。

例如:我想在某些存储库函数内多次调用connection.query或connection.execute。如果我不使用using语句什么时候我的连接会关闭?目标是使Web开发尽可能高效。

BaseRepository

public static string ConnectionString => @"Server=.;Database=applicationDb;User ID=sa;Password=Password12!";
protected SqlConnection _connection;
protected SqlConnection connection => _connection ?? (_connection = GetOpenConnection());

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

public SqlConnection GetClosedConnection()
{
    var conn = new SqlConnection(ConnectionString);
    if (conn.State != ConnectionState.Closed) throw new InvalidOperationException("should be closed!");
    return conn;
}

public void Dispose()
{
    _connection?.Dispose();
}

CustomerRepository:BaseRepository

使用BaseRepository设置它的方式。以下是否有任何区别:

public IEnumerable<Customer> GetCustomers()
{
    using (connection)
    {
        StringBuilder sql = new StringBuilder();
        sql.AppendLine("SELECT Id, Name, Email ");
        sql.AppendLine("FROM Customer;");

        StringBuilder deleteSql = new StringBuilder();
        deleteSql = new StringBuilder();
        deleteSql.AppendLine("DELETE FROM Xyz ");
        deleteSql.AppendLine("FROM CustomerId = @CustomerId;");
        connection.Execute(deleteSql.ToString(), new { CustomerId = 5 });

        return connection.Query<Customer>(sql.ToString()).ToList();
    }
}

没有使用的OR:

public IEnumerable<Customer> GetCustomers()
{
        StringBuilder sql = new StringBuilder();
        sql.AppendLine("SELECT Id, Name, Email ");
        sql.AppendLine("FROM Customer;");

        StringBuilder deleteSql = new StringBuilder();
        deleteSql = new StringBuilder();
        deleteSql.AppendLine("DELETE FROM Xyz ");
        deleteSql.AppendLine("FROM CustomerId = @CustomerId;");
        connection.Execute(deleteSql.ToString(), new { CustomerId = 5 });

        return connection.Query<Customer>(sql.ToString()).ToList();
}

2 个答案:

答案 0 :(得分:2)

我的建议是使用using语句,因为using语句的目的是当控件到达使用结束时它会释放使用块的对象并释放内存。它的目的不仅仅是自动连接关闭,基本上它会配置连接对象,显然连接也因此而关闭。

答案 1 :(得分:1)

您需要在using语句(或try...catch中)处理您的调用(如果您希望处理例外情况),它将关闭它并自动处理它。