繁体   English   中英

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

[英]Conversion error from database smallint into C# nullable int

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

我收到以下错误:

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

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

SELECT R.security_role_cd  FROM Security_Role R WHERE security_role_name = 'Admin'

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();

它只需要知道如何键入 null

roleID = readerRole.GetInt16(0) == 0 ? (int?)null : (int)readerRole.GetInt16(0);

我个人会缓存值:

int tmp = readerRole.GetInt16(0); // implicit widening to int here
roleID = tmp == 0 ? (int?)null : tmp;

虽然我也怀疑将0变为null的智慧 - 更好地使用IsDBNull - 类似于:

if(reader.IsDBNull(0)) {
    roleID = null;
} else {
    roleID = (int)readerRole.GetInt16(0);
}

尝试这个

roleID = readerRole.GetInt16(0) == 0 ? (int?) null : readerRole.GetInt16(0) ;

根据三元运算符的文档,冒号(:)两侧的数据类型必须相同。 正如你没有强制转换那样,无法确定null的类型(即,如果是nullable int,或null string,或null对象)

更新

roleID = readerRole.GetInt16(0) == 0 ? (int?) null : readerRole.GetInt32(0) ;

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM