从数据库smallint到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对象)
更新
上述就是C#学习教程:从数据库smallint到C#nullable int的转换错误分享的全部内容,如果对大家有所用处且需要了解更多关于C#学习教程,希望大家多多关注—计算机技术网(www.ctvol.com)!
roleID = readerRole.GetInt16(0) == 0 ? (int?) null : readerRole.GetInt32(0) ;
本文来自网络收集,不代表计算机技术网立场,如涉及侵权请联系管理员删除。
ctvol管理联系方式QQ:251552304
本文章地址:https://www.ctvol.com/cdevelopment/999883.html