I have this simple code working fine in runtime in my Controller, ASP Net 4.6 and SQL Server 2014, but when run in debug mode (step by step) and I stop de process in the middle of transaction scope, the changes in database are committed. How can it be possible?
void RootMethod()
{
using (TransactionScope scope = new TransactionScope())
{
DoSql("Update myTable Set " +
"MyField = 'value' " +
"Where " +
"Id = 'test');
//stop here
Console.WriteLine("OK");
DoSql("Update myTable Set " +
"MyField = 'secondValue' " +
"Where " +
"Id = 'test');
scope.Complete();
}
}
The code is simplified in order to minimize complexity as well as SQL statements. The "DoSql" function is a helper with the following code:
public static void DoSql(string cCmdSql)
{
string connStr = "uid=userdb;pwd=xxxxxx;server=MyServer;database=MyDatabase;Application Name=\"WebApp\";
using (SqlConnection conn = new SqlConnection(connStr))
{
try
{
conn.Open();
SqlCommand selectCmd = new SqlCommand(cCmdSql, conn);
SqlDataAdapter oAda = new SqlDataAdapter();
oAda.SelectCommand = selectCmd;
oAda.SelectCommand.CommandTimeout = 300;
DataSet oDs = new DataSet();
oAda.Fill(oDs);
}
catch (SqlException ex)
{
Console.WriteLine("SQL: " + cCmdSql + ex.Message);
throw;
}
}
return;
}
When I'm debugging a process in the middle of a transaction and I have to stop it to correct it, I need the transaction make a rollback and it doesn't.
But in runtime if I put a Transaction.Current.Rollback() or the sql statement fail, the transaction is rolled back.