I have 3 delete
queries executed by my sql command. The last of the three queries can only execute if there is no reference to it in other tables. It fails to execute if there is a reference. So, if the last delete fails, I want to rollback
to not lose the data that would be deleted in the previous 2 commands. This is why I need to use a SqlTransaction
.
The following is what I was able to come up with. It in fact prevents the loss of any data, however, I am unable to delete anything and am always getting the popup (meaning every time it is executed, it is caught).
protected void editDelete(object sender, DirectEventArgs e)
{
SqlConnection MyConnection = new SqlConnection();
MyConnection.ConnectionString = ConfigurationManager.ConnectionStrings["MyConnectionString"].ConnectionString;
MyConnection.Open();
// Start a local transaction.
SqlTransaction sqlTran = MyConnection.BeginTransaction();
try
{
SqlCommand MyCommand = new SqlCommand();
MyCommand.CommandText = /* 3 queries removed to shorten code */;
MyCommand.CommandType = CommandType.Text;
MyCommand.Connection = MyConnection;
SqlParameter p1 = new SqlParameter("@id", this.accountidEdit.Value);
MyCommand.Parameters.Add(p1);
MyCommand.ExecuteNonQuery();
MyConnection.Close();
/* reload and notification calls removed to shorten code */
}
catch (Exception)
{
sqlTran.Rollback();
X.Msg.Alert("Error", "Error.").Show();
}
}
In addition, I tried to find the problem by using:
catch (Exception sqlexception)
{
Console.WriteLine(sqlexception.Message);
sqlTran.Rollback();
X.Msg.Alert("Error", "Error.").Show();
}
but nothing ever wrote to the console.. weird?
Is this the proper way to execute a SqlTransaction
? I followed a guide from the microsoft site to do this. Why is it always being caught?
Thank you!