The code works perfectly without btw rollback.
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["dbconnection"].ConnectionString);
con.Open();
SqlTransaction tran = con.BeginTransaction();
try
{
//Adicionar Titular query----------------------------------------------------------------------------------------------------------------------------------
SqlCommand cmd2 = new SqlCommand("INSERT INTO Titular(nifTitular,nifEntidade,nome,emailTitular,contacto)" +
"VALUES(@nifTitular,@nifEntidade,@nome,@emailTitular,@contacto)" + "SELECT SCOPE_IDENTITY()", con);
cmd2.Parameters.AddWithValue("@nifTitular", Request.Form["nif"]);
cmd2.Parameters.AddWithValue("@nifEntidade", Request.Form["nife"]);
cmd2.Parameters.AddWithValue("@nome", Request.Form["nome"]);
cmd2.Parameters.AddWithValue("@emailtitular", Request.Form["email"]);
cmd2.Parameters.AddWithValue("@contacto", Request.Form["contacto"]);
//iNewRowIdentity passa a ter o ultimo idTitular inserido
int iNewRowIdentityTit = Convert.ToInt32(cmd2.ExecuteScalar());
tran.Commit();
ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "alertMessage", "alert('Registo feito com sucesso')", true);
}
catch (SqlException exception)
{
tran.Rollback();
Response.Write("<p>Error code " + exception.Number + ": " + exception.Message + "</p>");
}
finally
{
con.Close();
}
Give me this error.
ExecuteScalar requires the command to have a transaction when the binding assigned to the command is in a pending local transaction. The Transaction property of the command was not initialized.