.net - ExecuteScalar 函数失败。必须声明标量变量“@DeviceId”
问题描述
我有一个接收对象列表的控制器。首先,它使用 ExecuteScalar 检查表中是否已经存在这些对象。如果行已经存在,我们运行更新存储过程。如果没有,我们运行 Insert 存储过程。但是,我的代码在执行标量函数处失败,该函数告诉我们“必须声明标量变量@DeviceId”。我不确定错误消息是指查询还是 Sql 参数。
public BaseResponse Post([FromBody]List<PendingAttachment> pendingAttachmentRequest)
{
PendingAttachment pendingAttachment = new PendingAttachment();
List<SqlParameter> sqlParameters = new List<SqlParameter>()
{
new SqlParameter("@Datasource", pendingAttachment.DataSource),
new SqlParameter("@LastUpdated", pendingAttachment.LastUpdated),
new SqlParameter("@PendingCount", pendingAttachment.PendingCount),
new SqlParameter("@DeviceId", pendingAttachment.DeviceId),
new SqlParameter("@Username", pendingAttachment.UserName),
};
try
{
RequestHeaders headers = new RequestHeaders();
var query = "SELECT count(*) FROM PendingAttachments WHERE DeviceId = @DeviceId AND UserName = @UserName";
using (var onbaseConnection = MobileCompleteServer.Helpers.OnbaseAuth.Connect(headers))
{
var connectionString = System.Configuration.ConfigurationManager.AppSettings["ConnectionString"];
using (SqlConnection sqlConnection = new SqlConnection(connectionString))
{
sqlConnection.Open();
using (SqlCommand comm = new SqlCommand(query, sqlConnection))
{
comm.CommandType = System.Data.CommandType.Text;
foreach(PendingAttachment attachment in pendingAttachmentRequest)
{
comm.Parameters.AddRange(sqlParameters.ToArray());
comm.Parameters.Clear();
}
int rowCount = (int)comm.ExecuteScalar(); //FAILS HERE
if (rowCount > 0)
{
using (SqlCommand sqlComm = new SqlCommand("sp_UpdatePendingAttachments", sqlConnection))
{
sqlComm.CommandType = System.Data.CommandType.StoredProcedure;
foreach (PendingAttachment attachment in pendingAttachmentRequest)
{
sqlComm.Parameters.AddRange(sqlParameters.ToArray());
sqlComm.Parameters.Clear();
}
sqlComm.ExecuteNonQuery();
}
}
else
{
using (SqlCommand sqlCommand = new SqlCommand("sp_InsertPendingAttachments", sqlConnection))
{
sqlCommand.CommandType = System.Data.CommandType.StoredProcedure;
foreach(PendingAttachment attachment in pendingAttachmentRequest)
{
sqlCommand.Parameters.AddRange(sqlParameters.ToArray());
sqlCommand.Parameters.Clear();
}
sqlCommand.ExecuteNonQuery();
}
}
}
}
return new BaseResponse();
}
}
catch (Exception ex)
{
return new BaseResponse
{
Exception = ErrorCodes.Get(ex, ErrorCodes.PendingAttachmentError),
ExceptionStackTrace = ex.ToString()
};
}
}
}
解决方案
推荐阅读
- javascript - 在搜索输入框中添加清除按钮
- python - 使用 selenium-webdriver 无法通过 xpath 找到元素
- odoo - 使用 on 函数计算两个字段
- javascript - 代码行给了我一个错误“渲染错误:”RangeError:无效的数组长度“”,但是,该行仍然按照它的意思做
- php - 如何使用 Laravel 运行 AngularJS 项目
- matlab - 如果 y 方向设置为“反向”,如何在 Matlab 中修复矢量注释头的错误对齐
- r - 如何编写一个 R 函数,从列索引而不是值中给出基因名称作为输出并发出错误?
- ruby - 无法在 Rubymine 2019.1 中使用 jRuby 9.1.17 运行规范
- python - 如何从 csv 文件中读取二维字典?
- regex - 多行正则表达式在 ruby 中不起作用