I am making an application that will register an order and for that I need to use the transaction sentences. I have developed an attempt that I will attach below and the following error:
Unhandled exception of type 'System.InvalidOperationException' in System.Data.dll
Additional information: ExecuteNonQuery requires the command to have a transaction when the connection assigned to it is in a pending local transaction. The property has not been initialized Transaction of the command.
I really have no idea how to solve it, because I'm new in this transaction. If anyone can help me I would be very grateful
CODE: Transaction Class
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Data; using System.Data.SqlClient; using System.Data; using System.Data.SqlClient;
namespace CapaDatos { public class Transaccion { DataManager dataManager = new DataManager(); SqlDataReader leer; SqlCommand comando = new SqlCommand(); DataTable tabla = new DataTable();
public void RegistrarPedido(string descripcion, int idCliente, string
idRepartidor, double montoTotal)
{
comando.Connection = dataManager.AbrirConexion();
dataManager.BeginTransaction();
comando.CommandText = "INSERT INTO PEDIDOSCLIENTES VALUES ('" +
descripcion + "','" + idCliente + "','" + idRepartidor + "','" +
montoTotal + "')";
comando.ExecuteNonQuery();
dataManager.Commit();
} }
CODE: DataManager Class
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Data; using System.Data.SqlClient;
namespace CapaDatos { public class DataManager { SqlConnection Conexion = new SqlConnection(@"Data Source=TOSHIBA\SQLEXPRESS;Initial Catalog=baseDeDatosPedidos;Integrated Security=True"); SqlTransaction Transaccion;
public SqlConnection AbrirConexion()
{
if (Conexion.State == ConnectionState.Closed)
Conexion.Open();
return Conexion;
}
public SqlConnection CerrarConexion()
{
if (Conexion.State == ConnectionState.Open)
Conexion.Close();
return Conexion;
}
public void Commit()
{
if (Transaccion != null)
Transaccion.Commit();
}
public void BeginTransaction()
{
if (Conexion.State == ConnectionState.Open)
Transaccion = Conexion.BeginTransaction();
}
public void Rollback()
{
if (Transaccion != null)
Transaccion.Rollback();
}
} }