从数据库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对象)

更新

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