What is the use/advantage of using CommandBehavior.CloseConnection in ExecuteReader()

后端 未结 6 1960
甜味超标
甜味超标 2020-12-14 09:38

Can anyone tell me what is the CommandBehavior.CloseConnection and what is the use/benefit of passing this as a parameter in com.ExecuteReader(CommandBeha

6条回答
  •  伪装坚强ぢ
    2020-12-14 10:02

    Use CommandBehavior.CloseConnection in functions that create a connection but return a IDataReader. Be very careful to Dispose() of the IDbConnection on exceptions only before the reader is created:

    IDataReader ReadAll()
    {
        var connection = new SqlConnection(connectionString);
        try
        {
            connection.Open();
            var command = connection.CreateCommand();
            command.CommandText = "SELECT * FROM mytable";
            var result = command.ExecuteReader(CommandBehavior.CloseConnection);
            connection = null; // Don't dispose the connection.
            return result;
        }
        finally
        {
            if (connection != null)
                connection.Dispose();
        }
    }
    

提交回复
热议问题