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