How does Npgsql handle failed transactions?

another way could be:

using( var tx = connection.BeginTransaction())
{
    .. do som database stuff ..

    tx.Commit();
}

Dispose on a non committed transaction leads to a rollback. And resources are freed!


PostgreSQL will automatically abort, but not rollback, the transaction in case of an error.

The transaction is only done if you

  1. disconnect

  2. end the transaction with COMMIT or ROLLBACK (it will rollback in both cases)

All statements sent on the connection between the error and the end of the transaction will be ignored.

So yes, you should use a try / catch block and rollback.

A ROLLBACK will always undo the current transaction completely, no matter if there was an error or not.