Using for IDbConnection/IDbTransaction safe to use?

前端 未结 2 1080
臣服心动
臣服心动 2021-02-08 09:55

While my assumption may seem to sound subjective, after some research, I found that it\'s not uncommon to find developers who favour a dummy Try/Catch instead of us

相关标签:
2条回答
  • 2021-02-08 10:44

    I'm entirely with you on the connection; that should be using, and there is no need for the explicit Close(). The transaction is a little bit trickier; the code shown is certainly overkill at the moment, but it is not entirely defined that Dispose() should do a rollback. Actually, that is what tends to happen in every implementation I've looked at, but it is slightly vexing that even DbTransaction (which most providers use) doesn't actually do this. Contrast to TransactionScope where it is explicitly defined that a Dispose() without a commit counts as a rollback. Because of that, I tend to use (excuse the C#):

    using(var conn = GetOpenConnection())
    using(var tran = conn.BeginTransaction()) {
        try {
            // TODO: do work
            tran.Commit();
        } catch {
            tran.Rollback();
            throw;
        }
    }
    

    which is somewhere between the two in terms of complexity. It isn't messing around with null-checks, at least.

    0 讨论(0)
  • 2021-02-08 10:49

    What you're seeing is developers coding according to the documentation (a "Good Thing"). The base class DbTransaction (used for most data providers' transaction implementations) states clearly in its documentation:

    Dispose should rollback the transaction. However, the behavior of Dispose is provider specific, and should not replace calling Rollback.

    0 讨论(0)
提交回复
热议问题