I am after some help with a piece of code I have created, I am attempting to make an Async SQL call from c# within a transaction, for example I might be updating or deleting rows from a table.
This is what I have so far, but I cannot seem to find much information on doing this in a transaction, from what I have here and what I understand so far, I believe it may attempt to commit the transaction before the command has fully completed if the command is time-consuming. If you could advise / point me to 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();
}
}
}
Thanks,
Issuing a COMMIT TRANSACTION when @@TRANCOUNT is zero results in an error; there's no corresponding BEGIN TRANSACTION. You can't roll back a transaction after a COMMIT TRANSACTION statement is issued because the data modifications have been made a permanent part of the database.
ExecuteNonQueryAsync(CancellationToken) The default implementation invokes the synchronous ExecuteNonQuery() method and returns a completed task, blocking the calling thread.
This statement has the following syntax: commit [work]; Note: The optional work keyword is used only for compatibility with some versions of SQL. The commit statement terminates the current database transaction and commits any changes made by the transaction.
Your code looks good. I just added a try/catch on the execution of the command so you can roll back your transaction if it fails. Because you are using the await
keyword on the line await command.ExecuteNonQueryAsync();
execution will block until the method returns regardless of how long it takes (unless you get a timeout exception from the command itself in which case you should set the command's execution timeout higher or figure out why its taking so long).
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 {
tran.Rollback();
throw;
}
tran.Commit();
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With