转换错误从数据库中SMALLINT到C#可空INT [英] Conversion error from database smallint into C# nullable int
问题描述
我在 SMALLINT
数据类型的数据库security_role_cd列。我使用下面的code到可空INT
变量选择此列。
我收到以下错误:
错误3的条件EX pression类型无法确定,因为没有之间的空与短
隐式转换
什么是正确的code克服这种错误?
SELECT R.security_role_cd从Security_Role R其中security_role_name ='管理员'
C#
诠释? roleID = NULL;
字符串的CommandText =SELECT R.security_role_cd从Security_Role R其中security_role_name = @rolename;
SqlCommand的命令=新的SqlCommand(CommandText中,连接);
command.CommandType = System.Data.CommandType.Text;
command.Parameters.AddWithValue(@角色名,角色名);
SqlDataReader的readerRole = Command.ExecuteReader却();
如果(readerRole.HasRows)
{
而(readerRole.Read())
{
roleID = readerRole.GetInt16(0)== 0?空:readerRole.GetInt16(0);
}
}
readerRole.Close();
它只是需要知道如何的键入的的空
:
roleID = readerRole.GetInt16(0)== 0? (INT?)空:(INT)readerRole.GetInt16(0);
我个人倒缓存值,但:
INT TMP = readerRole.GetInt16(0); //隐式扩大在这里诠释
roleID = TMP == 0? (INT?)空:TMP;
虽然我也想叫成疑问转动的智慧 0
到空
- 最好使用 IsDBNull以便
- 是这样的:
如果(reader.IsDBNull(0)){
roleID = NULL;
} 其他 {
roleID =(int)的readerRole.GetInt16(0);
}
I have a security_role_cd column in database of smallint
datatype. I am selecting this column using following code into a nullable int
variable.
I am getting following error:
Error 3 Type of conditional expression cannot be determined because there is no implicit conversion between 'null' and 'short'
What is the correct code to overcome this error?
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();
It just needs to know how to type the null
:
roleID = readerRole.GetInt16(0) == 0 ? (int?)null : (int)readerRole.GetInt16(0);
Personally I'd cache the value though:
int tmp = readerRole.GetInt16(0); // implicit widening to int here
roleID = tmp == 0 ? (int?)null : tmp;
Although I'd also call into doubt the wisdom of turning a 0
into a null
- better to use IsDBNull
- something like:
if(reader.IsDBNull(0)) {
roleID = null;
} else {
roleID = (int)readerRole.GetInt16(0);
}
这篇关于转换错误从数据库中SMALLINT到C#可空INT的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!