从数据库smallint到C#nullable int的转换错误

LCJ*_*LCJ 2 .net c# ado.net

我在smallint数据类型的数据库中有一个security_role_cd列.我正在使用以下代码将此列选入nullable int变量.

我收到以下错误:

错误3无法确定条件表达式的类型,因为'null'和'short'之间没有隐式转换

克服此错误的正确代码是什么?

SELECT R.security_role_cd  FROM Security_Role R WHERE security_role_name = 'Admin'
Run Code Online (Sandbox Code Playgroud)

C#

        int? roleID = null;
        string commandText = "SELECT R.security_role_cd  FROM Security_Role R WHERE security_role_name = @roleName";
        SqlCommand command = new SqlCommand(commandText, connection);
        command.CommandType = System.Data.CommandType.Text;
        command.Parameters.AddWithValue("@roleName",roleName);
        SqlDataReader readerRole = command.ExecuteReader();
        if (readerRole.HasRows)
        {
            while (readerRole.Read())
            {
                roleID = readerRole.GetInt16(0) == 0 ? null : readerRole.GetInt16(0) ;

            }
        }
        readerRole.Close();
Run Code Online (Sandbox Code Playgroud)

Mar*_*ell 6

它只是需要知道如何键入null:

roleID = readerRole.GetInt16(0) == 0 ? (int?)null : (int)readerRole.GetInt16(0);
Run Code Online (Sandbox Code Playgroud)

就个人而言,我会缓存这个值:

int tmp = readerRole.GetInt16(0); // implicit widening to int here
roleID = tmp == 0 ? (int?)null : tmp;
Run Code Online (Sandbox Code Playgroud)

虽然我也怀疑将一个0变成一个null更好用的智慧IsDBNull- 比如:

if(reader.IsDBNull(0)) {
    roleID = null;
} else {
    roleID = (int)readerRole.GetInt16(0);
}
Run Code Online (Sandbox Code Playgroud)