如何从SQL Server表中转换TinyInt值?

问题描述

我有sql Server(Express)表:

enter image description here

...具有tinyint的GenreId(最多只有几十种不同的流派)。

此C#代码失败,显示“指定的转换无效”。

int genreId = 0;
. . .
genreId = GetGenreIdForGenre(_genre);

故障点的“ _genre”值为“冒险”。对GetGenreIdForGenre()的调用应返回“ 1”:

enter image description here

这是在GetGenreIdForGenre()中失败的行:

return (int)command.ExecuteScalar();

在上下文中,GetGenreIdForGenre()方法为:

private int GetGenreIdForGenre(string genre)
{
    try
    {
        string qry = "SELECT GenreId FROM dbo.GENRES WHERE Genre = @genre";
        using (sqlConnection connection = new sqlConnection(_connectionString))
        {
            using (sqlCommand command = new sqlCommand(qry,connection))
            {
                command.Parameters.AddWithValue("@genre",genre);
                connection.open();
                return (int)command.ExecuteScalar();
            }
        }
     }
     catch (Exception ex)
     {
         MessageBox.Show(ex.Message);
         return 0;
     }
 }

没有(tinyint)转换可用。 Int32也失败。我需要怎么做才能检索tinyint值?

解决方法

command.ExecuteScalar的返回类型为object,因此该值返回一个装箱的byte。将其投射到int之前,必须先将byte拆箱:

return (byte)reader.ExecuteScalar();

解压缩到byte的装箱后,它将使用到int的可用隐式转换(以匹配方法的返回类型),因此您不需要其他强制转换。

,

在查询中进行投射:

string qry = "SELECT CAST(GenreId as int) FROM dbo.GENRES WHERE Genre = @genre";

那样,您就不必担心客户端转换。