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);
‘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.