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 = 开发者_JS百科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);
ExecuteScalar() doesn't return type bool:
Type: System.Object
The first column of the first row in the result set, or a null reference (Nothing in Visual Basic) if the result set is empty. Returns a maximum of 2033 characters.
Also, you create the parameter with the name "@key" and then use a different name in this line:
command.Parameters["@activationkey"].Value = guid;
I think you mean @key
instead of @activationkey
. Then you can add a parameter like this:
command.Parameters.Add(new SqlParameter
{
ParameterName = "@key",
SqlDbType = SqlDbType.UniqueIdentifier,
Value = new Guid(key)
});
'Specified cast is not valid' means, that you are casting wrong and this is the only place you're doing this:
return (bool)command.ExecuteScalar();
Check this value. Either it is DBNull or another data type. Try debugging it, to find out the data type.
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 be key
command.Parameters["@key"].Value = guid;
精彩评论