[踩坑记录] ASP.NET Core System.Data.SqlTypes.SqlNullValueException: 数据为空。不能对空值调用此方法

62 篇文章 6 订阅
35 篇文章 1 订阅

问题是出在这里的:

SoftwareInfo result = new SoftwareInfo(
reader.GetString(1),              // reader 是 MySqlDataReader 实例
reader.GetString(7))
{
    ID = reader.GetInt32(0),
    Label = reader.GetString(2),
    Coder = reader.GetString(3),
    DownloadCount = reader.GetInt32(4),
    Stars = reader.GetFloat(5),
    Introduction = reader.GetString(6)
};

return result;

解决方案:

第一种: 添加 Null 检查, 在调用 GetString, GetInt32, GetFloat 这类包含具体的类型转换的函数前, 先调用 IsDBNull 检查这条数据是不是 Null.

SoftwareInfo currentInfo = new SoftwareInfo(
reader.GetString(1),
reader.GetString(7))
{
    ID = reader.GetInt32(0),
    Label = reader.IsDBNull(2) ? null : reader.GetString(2),
    Coder = reader.IsDBNull(3) ? null : reader.GetString(3),
    DownloadCount = reader.IsDBNull(4) ? 0 : reader.GetInt32(4),
    Stars = reader.IsDBNull(5) ? 0 : reader.IsDBNull(5) ? 0 : reader.GetFloat(5),
    Introduction = reader.IsDBNull(6) ? null : reader.GetString(6)
};

return currentInfo;

第二种: 直接指定数据库的字段不可为 Null, 从根本上杜绝空值

alter table tablename modify columnname not null;

原因:

如果数据是 Null, 就无法调用包含具体类型的方法, 因为它们内部涉及到类型转换.

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值