I am creating a project in C# with sql server 2017 and I have the DAO_Socio class, which is responsible for assembling the objects that communicate with the Database:
public Inscripcion getSociosPorNombre(string nombreSocio)
{
string sp, columna, parametro;
sp = "sp_listar_socios_por_nombre";
columna = "@nombre";
parametro = nombreSocio;
DataTable tabla = getSociosPorNombre(sp,columna,parametro);
Inscripcion inscripcion = new Inscripcion();
foreach (DataRow fila in tabla.Rows)
{
inscripcion = mapper(fila);
}
return inscripcion;
}
In turn, the DBHelper class is responsible for communicating with the database.
The following method allows me to bring a table from the database, through a stored procedure:
public DataTable getSociosPorNombre(string storedProcedure, string nombreColumna, string parametro)
{
SqlConnection cnn = new SqlConnection();
SqlCommand cmd = new SqlCommand();
DataTable tabla = new DataTable();
try
{
cnn.ConnectionString = string_conexion;
cnn.Open();
cmd.Connection = cnn;
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandText = storedProcedure;
cmd.Parameters.AddWithValue(nombreColumna,parametro);
tabla.Load(cmd.ExecuteReader());
return tabla;
}
catch (SqlException ex)
{
MessageBox.Show("EXPLOTO EL HELPER", "ERROR", MessageBoxButtons.OK, MessageBoxIcon.Error);
throw (ex);
}
finally
{
this.CloseConnection(cnn);
}
}
The problem with this method is that I can only pass a single parameter to it. How do I make the method execute any type of SP, with any number of parameters without having to specify the name of the column and the value that I pass to it.
You can use the AddRange function to add a list of SqlParameter like so:
and you could consume it in multiple ways, here is one way: