0
I am a beginner and I have a code in which I need to insert multiple products inside a shopping list, however, in the code I made, it is only possible to insert one JSON at a time.
[HttpPost]
[Route("lista/addproduto")]
public HttpResponseMessage AddProdutoNaLista(ProdutosLista prod)
{
try
{
List<ProdutosLista> lstProdLista = new List<ProdutosLista>();
using (SqlConnection connection = new SqlConnection(ConnectionString))
{
connection.Open();
using (SqlCommand command = new SqlCommand())
{
command.Connection = connection;
command.CommandText = "INSERT INTO PRODLISTA VALUES (@codigo, @nome, @cbarra, @pco_remar, @unidade, @quantidade, @peso, @pco_total, @id_lista)";
command.Parameters.AddWithValue("@codigo", prod.CodProduto);
command.Parameters.AddWithValue("@nome", prod.Nome);
command.Parameters.AddWithValue("@cbarra", prod.CodBarra);
command.Parameters.AddWithValue("@pco_remar", prod.Preco);
command.Parameters.AddWithValue("@unidade", prod.Unidade);
command.Parameters.AddWithValue("@quantidade", prod.Quantidade);
command.Parameters.AddWithValue("@peso", prod.Peso);
command.Parameters.AddWithValue("@pco_total", prod.PrecoTotal);
command.Parameters.AddWithValue("@id_lista", prod.IdLista);
lstProdLista.Add(prod);
if (prod.CodProduto != 0 && prod.Preco != 0 && prod.PrecoTotal != 0)
{
command.ExecuteNonQuery();
}
}
connection.Close();
}
return Request.CreateResponse(HttpStatusCode.OK, lstProdLista.ToArray());
}
catch (Exception ex)
{
return Request.CreateResponse(HttpStatusCode.BadRequest, ex.Message);
}
}
If I pass only one JSON, it normally inserts, but if I pass more than one JSON, it returns the following error in Postman:
"Undefined object reference for an object instance."
I imagine it’s because I’m assigning more than one value to the properties, I thought about putting inside a while, but I can’t think about the condition of the command.
For this you would have to receive as parameter a list of objects of type
ProdutosLista
. At the moment you are only passing one instance of the object, so you can only insert one at a time.– João Martins