I was reading about transactions and saw this example from Microsoft docs. The gist from the example:
using (SqlConnection connection = new SqlConnection(connectionString))
{
connection.Open();
SqlTransaction sqlTran = connection.BeginTransaction();
try
{
// Execute some commands
sqlTran.Commit();
}
catch (Exception ex)
{
try
{
// Attempt to roll back the transaction.
sqlTran.Rollback();
}
catch (Exception exRollback)
{
Console.WriteLine(exRollback.Message);
}
}
}
What I don't understand here is why do we need an explicit rollback? As far as I can see the using statement will close the connection and rollback the transaction that was not committed?
The answers for a question here are contradicting, one saying that transaction is not rolled back, while the other saying that Ado.Net connection pooling will fix it and transaction is rolled back before connection is returned to the pool (which makes sense actually).
P.S. I have actually tried to check it and it seems the disposing of the connection is enough for the transaction to be rolled back. But I guess there are some circumstances where that might not be enough