Using for IDbConnection/IDbTransaction safe to use?

前端 未结 2 1079
臣服心动
臣服心动 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.

提交回复
热议问题