无法将 guid 作为唯一标识符传递给存储过程
我有一个存储过程,它采用唯一标识符作为参数。
它应该像这样工作(我没有写这个):
SqlCommand command = new SqlCommand("[CheckActivation]", Conn)
{
CommandType = CommandType.StoredProcedure
};
command.Parameters.AddWithValue("@key", key);
return (bool)command.ExecuteScalar();
其中 key 是一个字符串,但它不是。我总是收到“指定的演员无效”异常。
所以我将其重写为:
Guid guid = new Guid(key);
using (var command = Conn.CreateCommand())
{
command.CommandText = "[CheckActivation]";
command.CommandType = CommandType.StoredProcedure;
command.Parameters.Add("@key", SqlDbType.UniqueIdentifier);
command.Parameters["@key"].Value = guid;
return (bool)command.ExecuteScalar();
}
guid 是具有正确值的 Guid 对象,但我仍然遇到相同的异常。
这里出了什么问题?
解决方案:问题出在 return 语句中的强制转换。 sp 返回一个不能转换为 bool 的 int 值:
return ((int)command.ExecuteScalar() == 1);
I have a stored procedure that takes a uniqueidentifier as parameter.
It is supposed to work like this (I didn't write this):
SqlCommand command = new SqlCommand("[CheckActivation]", Conn)
{
CommandType = CommandType.StoredProcedure
};
command.Parameters.AddWithValue("@key", key);
return (bool)command.ExecuteScalar();
where key is a string, but it does not. I alway get an 'Specified cast is not valid' exception.
So I rewrote it to:
Guid guid = new Guid(key);
using (var command = Conn.CreateCommand())
{
command.CommandText = "[CheckActivation]";
command.CommandType = CommandType.StoredProcedure;
command.Parameters.Add("@key", SqlDbType.UniqueIdentifier);
command.Parameters["@key"].Value = guid;
return (bool)command.ExecuteScalar();
}
guid is a Guid object with the correnct value, but I still get the same exception.
What is going wrong here?
Solution: The problem was the cast in the return statement. The sp returns an int value that cannot be casted to a bool:
return ((int)command.ExecuteScalar() == 1);
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
ExecuteScalar() 不返回类型布尔:
此外,您还可以使用名称“@key”创建参数,然后在此行中使用不同的名称:
ExecuteScalar() doesn't return type bool:
Also, you create the parameter with the name "@key" and then use a different name in this line:
我认为你的意思是
@key
而不是@activationkey
。然后你可以添加这样的参数:I think you mean
@key
instead of@activationkey
. Then you can add a parameter like this:“指定的转换无效”意味着您转换错误,这是您执行此操作的唯一位置:
检查此值。它可以是 DBNull 或其他数据类型。尝试调试它,找出数据类型。
'Specified cast is not valid' means, that you are casting wrong and this is the only place you're doing this:
Check this value. Either it is DBNull or another data type. Try debugging it, to find out the data type.
您指定参数
“@key”
作为唯一标识符类型,然后将
guid
设置为参数“@activationkey”
,该参数具有没有被宣布。我认为您不应该将值设置为
"@activationkey"
它应该是key
command.Parameters["@key"].Value = guid;< /代码>
You specify a parameter
"@key"
, as unique identifier type,then you are setting the
guid
to parameter"@activationkey"
, that has not been declared.I think that you should instead of setting value to
"@activationkey"
it shluld bekey
command.Parameters["@key"].Value = guid;