为了账号安全,请及时绑定邮箱和手机立即绑定

调用存储过程时出错返回值错误数据类型 nvarchar(max) 为 int

调用存储过程时出错返回值错误数据类型 nvarchar(max) 为 int

C#
森林海 2023-07-22 18:35:40
我调用 astored procedure并且它有一个int返回值。但是,将值返回到我的后端时出现错误。public async Task<string> CreatePortfolio(Portfolio portfolio){    string statusMessage;    using (SqlConnection conn = new SqlConnection(Connection))    {        SqlParameter returnValue = new SqlParameter(); //Holds the bit that determines if insert was successful or not        SqlCommand command;        command = new SqlCommand();        command.Connection = conn;        conn.Open();        command.CommandType = CommandType.StoredProcedure;        command.CommandText = "USP_Add_Portfolio";        command.Parameters.AddWithValue("@portfolioName", portfolio.PortfolioName);        command.Parameters.AddWithValue("@description", portfolio.Description);        command.Parameters.AddWithValue("@createID", portfolio.CreateID);        command.Parameters.AddWithValue("@updateID", portfolio.UpdateID);        command.Parameters.AddWithValue("@statusMessage", SqlDbType.NVarChar).Direction = ParameterDirection.Output;        returnValue.Direction = ParameterDirection.ReturnValue;        command.Parameters.Add(returnValue);        int i = await command.ExecuteNonQueryAsync().ConfigureAwait(false);        if(i == 1)        {            statusMessage = command.Parameters["@statusMessage"].Value.ToString();        }        else        {            statusMessage = "Error while adding please contact your administrator";        }    }    return statusMessage;}存储过程完成并添加新记录,但出现错误int i = await command.ExecuteNonQueryAsync().ConfigureAwait(false);错误:期待一个 int 但得到 nvarchar
查看完整描述

2 回答

?
狐的传说

TA贡献1804条经验 获得超3个赞

ExecuteNonQuery(暂时不用担心异步...)返回 UPDATE、INSERT、DELETE 影响的行数,否则返回 -1。它不直接从存储过程返回信息。

在上面的例子中,我认为你应该在没有“int i ="的情况下调用“await”,而不用担心调用的返回值ExecuteNonQueryAsync。相反,在该值之后,查看 中的值returnValue.Value,这将是“return”参数的值。它是一个对象,因此请验证类型或使用Convert.ToInt32().


查看完整回答
反对 回复 2023-07-22
?
函数式编程

TA贡献1807条经验 获得超9个赞

这看起来不正确,因为SqlDbType.NVarChar是一个枚举值:

command.Parameters.AddWithValue("@statusMessage", SqlDbType.NVarChar).Direction = ParameterDirection.Output;

如果你改用这个会发生什么:

command.Parameters.Add(new SqlParameter("@statusMessage", SqlDbType.NVarChar, -1)).Direction = ParameterDirection.Output;


查看完整回答
反对 回复 2023-07-22
  • 2 回答
  • 0 关注
  • 104 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信