次の SQL Server (Express) テーブルがあります。
... TinyInt の GenreId を使用します (せいぜい数十の異なるジャンルしかありません)。
この C# コードは失敗し、「指定されたキャストは無効です。」
int genreId = 0;
. . .
genreId = GetGenreIdForGenre(_genre);
失敗時の「_genre」の値は「Adventure」です。GetGenreIdForGenre() への呼び出しは「1」を返す必要があります。
これは、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 値を取得するにはどうすればよいですか?