Microsoft.Data.SqlClient.SqlException: 'Procedure or function 'USP_GUARDAR_CLIENTE' expects parameter '@Nombre', which was not supplied.'

Carlos J. Paco Quezada 5 Reputation points
2023-06-30T09:07:05.0533333+00:00
I use Visual Studio Community 2022 and SQL Server Management Studio M 2019
CONTROLLER:

using System.Data;
using Microsoft.AspNetCore.Mvc;
using Capa.Datos;
using Capa.Modelo;
using Microsoft.Data.SqlClient;
using Microsoft.Extensions.Configuration;

namespace CPV_SistemaWeb.Controllers
{
    public class ClientesController : Controller
    {
        private readonly IConfiguration config;

        public ClientesController(IConfiguration _config)
        {
            config = _config;
        }
        public IActionResult Index()
        {
            return View();
        }


        public JsonResult Obtener()
        {
            List<Cliente> Lista = CD_Clientes.Instancia.OBTENERCLIENTE();
            return Json(new { data = Lista });
        }

        public JsonResult Guardar(Cliente cliente)
        {
            string connectionString = config.GetConnectionString("CadenaSQL");
            using (SqlConnection connection = new SqlConnection(connectionString))
            {
                connection.Open();
                using (SqlCommand command = new SqlCommand("USP_GUARDAR_CLIENTE", connection))
                {
                    command.CommandType = CommandType.StoredProcedure;
                    command.Parameters.AddWithValue("@Nombre", cliente.Nombre);
                    command.Parameters.AddWithValue("@TipoDocumento", cliente.TipoDocum);
                    command.Parameters.AddWithValue("@NumeroDocumento", cliente.NumDocum);
                    command.Parameters.AddWithValue("@Direccion", cliente.Direccion);
                    command.Parameters.AddWithValue("@Telefono", cliente.Telefono);
                    command.Parameters.AddWithValue("@Email", cliente.Email);
                    command.Parameters.AddWithValue("@Activo", cliente.Activo);
                    command.ExecuteNonQuery();
                }
            }
            return Json(new { success = true });
        }
    }
 }   
SQL Server:

--TABLA CLIENTES 
if not exists (SELECT * FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'dbo' AND TABLE_NAME = 'Clientes') 
create table Clientes( 	
IdCliente int primary key identity(1,1), 	
Nombre Varchar (40), 	
TipoDocum Varchar (10), 	
NumDocum int, 	
Direccion Varchar (40), 	
Telefono int, 	
Email Varchar (40) , 	
Activo bit, 	
FechaRegistro datetime default getdate() );


STORED PROCEDURE:

CREATE PROCEDURE USP_GUARDAR_CLIENTE 	
@Nombre VARCHAR(40), 	
@TipoDocum VARCHAR(10), 	
@NumDocum INT, 	
@Direccion VARCHAR(40), 	
@Telefono INT, 	
@Email VARCHAR(40), 	
@Activo BIT, 	
@Resultado INT OUTPUT 
AS 
BEGIN 
	SET NOCOUNT ON;
  	BEGIN TRY
 		BEGIN TRANSACTION;
  		IF NOT EXISTS (SELECT * FROM Clientes WHERE NumDocum = @NumDocum)
 		BEGIN
 			INSERT INTO Clientes (Nombre, TipoDocum, NumDocum, Direccion, Telefono, Email, Activo)
 			VALUES (@Nombre, @TipoDocum, @NumDocum, @Direccion, @Telefono, @Email, @Activo);
  			SET @Resultado = 1; -- Inserción exitosa
 		END
 		ELSE
 		BEGIN
 			SET @Resultado = 0; -- Registro ya existe, no se realiza la operación
 		END 
 		COMMIT TRANSACTION;
 	END TRY
 	BEGIN CATCH
 		IF @@TRANCOUNT > 0
 			ROLLBACK TRANSACTION;
  		SET @Resultado = 0; -- Error durante la operación
 	END CATCH;
 END
ASP.NET
ASP.NET
A set of technologies in the .NET Framework for building web applications and XML web services.
3,267 questions
Visual Studio
Visual Studio
A family of Microsoft suites of integrated development tools for building applications for Windows, the web and mobile devices.
4,620 questions
SQL Server
SQL Server
A family of Microsoft relational database management and analysis systems for e-commerce, line-of-business, and data warehousing solutions.
12,754 questions
C#
C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
10,274 questions
{count} vote

2 answers

Sort by: Most helpful
  1. Dan Guzman 9,211 Reputation points
    2023-06-30T10:01:26.27+00:00

    Check the value of cliente.Nombre (and the others) to ensure it is not null. If you need to insert a NULL value, use DBNull.Value. Also, avoid using AddWithValue.

    1 person found this answer helpful.
    0 comments No comments

  2. Olaf Helper 40,901 Reputation points
    2023-06-30T10:05:32.2133333+00:00

    C#: command.Parameters.AddWithValue("@ NumeroDocumento", cliente.NumDocum); Stored procedure: @ NumDocum INT,

    And as may follow up failure: parameter names are different: C# NumeroDocumento vs SQL NumDocum