我正在使用 SqlDataReader 从 SQL Server 2012 数据库中获取数据:
SqlConnection connection = (SqlConnection)_db.Database.GetDbConnection();
await connection.OpenAsync();
SqlCommand command = new SqlCommand("dbo.[sp_MyStoredPrc] @InputId=1", connection);
var reader = await command.ExecuteReaderAsync();
if (reader.HasRows)
{
while (reader.Read())
{
int? var1 = (int?)reader["Column1Name"];
}
}
读取 NULL 时 int
来自数据库的字段,
reader["Column1Name"]
为空,因此代码在运行时抛出 InvalidCastException。
我试过了
reader.GetInt32(reader.GetOrdinal("Column1Name"))
但这会抛出 System.Data.SqlTypes.SqlNullValueException。
我也试过
reader.GetSqlInt32(reader.GetOrdinal("Column1Name"))
返回null,但是类型是SqlInt32
而不是 int?
如我所愿。
我最后做了
if (!reader.IsDBNull(reader.GetOrdinal("Column1Name")))
int? var1 = (int?)reader["Column1Name"];
有效。
问题:
有没有比调用
IsDBNull
更简单的方法呢?方法?为什么
reader["Column1Name"]
返回空白而不是null
如果 db 值为 NULL 且字段为int
?
最佳答案
Why does
reader["Column1Name"]
return blank instead of null if the db value is null and the field is anint
?
实际上,reader["Column1Name"]
返回 DBNull.Value如果数据库值为 NULL。 (在 Visual Studio 调试器中,该值显示为空白,因为 DBNull.ToString() 返回空字符串。)您不能使用强制转换将 DBNull.Value
直接转换为 int?
运营商。
Isn't there a simpler way then calling the
IsDBNull
method?
是的,使用 as
运算符而不是强制转换:
int? var1 = reader["Column1Name"] as int?;
因为 DBNull.Value
不是 int
,as
运算符返回 null
。
关于c# - SqlDataReader 为 int 字段返回空白而不是 null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34929972/