If you have to add the parameter and then delete it to add again because in your case it is an item interaction and you can still change the CommandText
out of foreach
, you only need to know this once, example :
cmd.CommandText = "INSERT INTO MinhaTabela (Coluna_A, Coluna_B, Coluna_C) " +
"VALUES (@Val_A, @Val_B, @Val_C)";
foreach (var item in pedidos)
{
cmd.Parameters.AddWithValue("@Val_A", item.AttributoA);
cmd.Parameters.AddWithValue("@Val_B", item.AttributoB);
cmd.Parameters.AddWithValue("@Val_C", item.AttributoC);
cmd.ExecuteNonQuery();
cmd.Parameters.Clear(); // adicione essa linha para limpar os parametros existentes.
}
has another way that would be to use the same parameter created and change its value, but, your code would have to be checking for the existence of the parameter created, I believe it is more practical to clear the parameters and add again, but, a example addition as well:
cmd.CommandText = "INSERT INTO MinhaTabela (Coluna_A, Coluna_B, Coluna_C) " +
"VALUES (@Val_A, @Val_B, @Val_C)";
foreach (var item in pedidos)
{
if (command.Parameters.Contains("@Val_A"))
{
command.Parameters["@Val_A"].Value = item.AttributoA;
}
else
{
command.Parameters.AddWithValue("@Val_A", item.AttributoA);
}
if (command.Parameters.Contains("@Val_B"))
{
command.Parameters["@Val_B"].Value = item.AttributoB;
}
else
{
command.Parameters.AddWithValue("@Val_B", item.AttributoB);
}
if (command.Parameters.Contains("@Val_C"))
{
command.Parameters["@Val_C"].Value = item.AttributoC;
}
else
{
command.Parameters.AddWithValue("@Val_C", item.AttributoC);
}
}