In the IDisposable.Dispose method is there a way to figure out if an exception is being thrown?
using (MyWrapper wrapper = new MyWrapper())
{
Now, in 2017, this is the generic way to do it, incl handling rollback for exceptions.
public static T WithinTransaction(this IDbConnection cnn, Func fn)
{
cnn.Open();
using (var transaction = cnn.BeginTransaction())
{
try
{
T res = fn(transaction);
transaction.Commit();
return res;
}
catch (Exception)
{
transaction.Rollback();
throw;
}
finally
{
cnn.Close();
}
}
}
and you call it like this:
cnn.WithinTransaction(
transaction =>
{
var affected = ..sqlcalls..(cnn, ..., transaction);
return affected;
});