即使在提供参数后抛出异常 "Procedure or function expects parameter, which was not supplied."

Exception "Procedure or function expects parameter, which was not supplied." thrown even after supplying the parameter

我正在尝试使用 C# 方法调用的存储过程在数据库中插入一些条目,如下所示:

public int addProfile(UserProfile NewUserPro)
{
    DataSet ds = ExecuteStoredProcedure("AddNewPro", new SqlParameter[]{
                new SqlParameter("@UserID", NewUserPro.UsrId),
                new SqlParameter("@Type", NewUserPro.Type),
                new SqlParameter("@Phone", NewUserPro.Phone),
                new SqlParameter("@Name", NewUserPro.Name),
                new SqlParameter("@FatherName", NewUserPro.FatherName),
                new SqlParameter("@GroupID", NewUserPro.GroupID),
                new SqlParameter("@IsPublic", 0)});
            return int.Parse(ds.Tables[0].Rows[0][0].ToString());
}

ExecuteStoredProcedure()是我创建的C#方法。它执行指定的存储过程和 returns 输出为 DataSet。这是该函数的定义:

public DataSet ExecuteStoredProcedure(string ProcedureName, SqlParameter[] Parameters)
{
    try
    {
         using (SqlCommand com = new SqlCommand("[dbo]." + ProcedureName))
         {
              com.CommandType = CommandType.StoredProcedure;
              foreach (SqlParameter sp in Parameters)
                   com.Parameters.Add(sp);
              return SelectDataSet(com);
         }
    }
    catch (Exception e)
    {
        throw e;
    }
}   

正如您在 addProfile() 方法中看到的那样,我已经提供了 @IsPublic 参数,但它仍然抛出以下异常:

Procedure or function 'AddNewPro' expects parameter '@IsPublic', which was not supplied.

@IsPublic 参数是一个 int 参数,它将值保存到 [IsPublic] 字段,该字段是 table 中的 int 字段 null 允许。

更新 1

我正在包括存储过程的输入参数。我认为这就足够了吗?如果您愿意,我可以包含完整的存储过程,但这是一个冗长的代码,并且由于某些保密原因,我不得不删减一些行。

ALTER PROCEDURE [dbo].[AddNewPro]
    @UserID int,
    @Name NVARCHAR(MAX),
    @Type int,
    @Phone VARCHAR(MAX),
    @GroupID int,
    @FatherName VARCHAR(MAX),
    @IsPublic int
AS

更新 2

好的,我找到了一些解决方案的提示。当我把断点放在ExecuteStoredProcedure的第一行时,我发现它获取@IsPublic的值为null。但是我在添加参数时提供了值。为什么会这样?

sqlparameter 将零作为对象读取。

小心使用零,阅读这篇文章post link

必须先将零转换为整数类型。 您的代码应如下所示。

new SqlParameter("@IsPublic", Convert.ToInt32(0));