This code came from https://learn.microsoft.com/en-us/dotnet/framework/data/adonet/asynchronous-programming. I modified it to match my Azure database table for an assertion of success. You will receive a row id = 1 from you're line 17 specification of var rows = await.cmd.ExecuteNonQueryAsync(); You must wrap your command.ExecuteNonQueryAsync in try catch incase you have invalid command. Good luck.
[TestClass]
public class UnitTest1
{
[TestMethod]
public void TestInsert()
{
var str = System.Configuration.ConfigurationManager.
ConnectionStrings["DefaultConnection"].ConnectionString;
Task task = ExecuteSqlTransaction(str);
System.Threading.Tasks.Task.Run(() => task).GetAwaiter().GetResult();
}
public async Task ExecuteSqlTransaction(string connectionString)
{
using (SqlConnection connection = new SqlConnection(connectionString))
{
await connection.OpenAsync();
SqlCommand command = connection.CreateCommand();
SqlTransaction transaction = null;
// Start a local transaction.
transaction = await Task.Run<SqlTransaction>(
() => connection.BeginTransaction("SampleTransaction")
);
// Must assign both transaction object and connection
// to Command object for a pending local transaction
command.Connection = connection;
command.Transaction = transaction;
try
{
command.CommandText =
"Insert into Table(A, B, C, D, E, F)" +
" VALUES ('Description', '42', '0', '3.14', '1.59','Title')";
var rows = await command.ExecuteNonQueryAsync();
// Attempt to commit the transaction.
await Task.Run(() => transaction.Commit());
Console.WriteLine("Inserted");
}
catch (Exception ex)
{
Console.WriteLine("Commit Exception Type: {0}", ex.GetType());
Console.WriteLine(" Message: {0}", ex.Message);
// Attempt to roll back the transaction.
try
{
transaction.Rollback();
}
catch (Exception ex2)
{
// This catch block will handle any errors that may have occurred
// on the server that would cause the rollback to fail, such as
// a closed connection.
Console.WriteLine("Rollback Exception Type: {0}", ex2.GetType());
Console.WriteLine(" Message: {0}", ex2.Message);
}
}
}
}
}