ExecuteNonQueryAsync and commit in SQL transaction

I will help a little with the piece of code I created, I am trying to make an Async SQL call from C # inside a transaction, for example, I could update or delete rows from a table.

This is what I have so far, but I can not find much information about this in the transaction, from what I have and what I understand so far, I believe that he can try to complete the transaction before the team completely completed if the team takes a long time. If you could advise / give me an example, I would really appreciate it.

var sqlQuery = "delete from table";
        using (var connection = new SqlConnection(ConnectionString))
        {
            await connection.OpenAsync();
            using (var tran = connection.BeginTransaction())
            {
                using (var command = new SqlCommand(sqlQuery, connection, tran))
                {
                    await command.ExecuteNonQueryAsync();
                    tran.Commit();
                }
            }
        }

Thank,

+4
source share
1 answer

. try/catch , , . await await command.ExecuteNonQueryAsync();, , , ( , , ).

    var sqlQuery = "delete from table";
    using (var connection = new SqlConnection(ConnectionString))
    {
        await connection.OpenAsync();
        using (var tran = connection.BeginTransaction())
        {
            using (var command = new SqlCommand(sqlQuery, connection, tran))
            {
                try {
                    await command.ExecuteNonQueryAsync();
                } catch(Exception){
                    tran.Rollback();
                    throw;
                }
                tran.Commit();
            }
        }
    }
+5

All Articles