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
I've found the best use of CommandBehavior.CloseConnection
is when you want to write code that is flexible enough to be used in a transaction (which implies a shared connection for all queries). Consider:
public DbDataReader GetReader(DbCommand cmd, bool close = true)
{
if(close)
return cmd.ExecuteReader(CommandBehavior.CloseConnection);
return cmd.ExecuteReader();
}
If you are running a read operation as part of a bigger transaction, you would want to pass false
to this method. In either case, you should still use a using
statement to do the actual read.
Not in a transaction:
using(var reader = GetReader(cmd, true))
{
while(reader.Read())
...
}
In a transaction, maybe checking for the existence of a record:
bool exists = false;
using(var reader = GetReader(cmd, false))
{
if(reader.Read())
exists = reader.GetBoolean(0);
}
The first example will close the reader AND the connection. The second one (transactional) will still close the reader, but not the connection.