处理 GetSQLDateTime 和 GetSQLMoney 中的空值

Handling Null values in GetSQLDateTime and GetSQLMoney

作为我正在编写的导入的一部分,我正在使用参数化值,但是我要导出到的数据库无法处理 NULL 值,因此我需要找到一种方法来处理 NULL 值。

我得到的最接近的是:

if (tenantexportReader.GetSqlMoney(8).ToDecimal().Equals(null))
{
     tenantimportCommand.Parameters["PRICEFINAL"].Value = "0.00";
} 
else 
{
     tenantimportCommand.Parameters["PRICEFINAL"].Value = tenantexportReader.GetSqlMoney(8).ToDecimal();
}

以及与 SQLDateTime 类似的事情

if (tenantexportReader.GetDateTime(9).ToShortDateString().Equals(null))
{
    tenantimportCommand.Parameters["TENSDATE"].Value = "0.00";
}
else
{
     tenantimportCommand.Parameters["TENSDATE"].Value = tenantexportReader.GetDateTime(9).ToShortDateString();
}  

但这似乎不起作用,相反我收到了以下信息:

Message=Data is Null. This method or property cannot be called on Null values.

而不是

if (tenantexportReader.GetSqlMoney(8).ToDecimal().Equals(null))

你可能应该使用

if (tenantexportReader.IsDbNull(8))

由于数据库中的值为 NULL(在 c# 中为 DbNull.Value),我假设 GetSqlMoneyGetSqlDateTime 抛出了您收到的异常。 DbNull.Value 无法转换为 SqlMoneyDateTime
在调用 GetSqlMoneyGetSqlDateTime.

之前通过 IsDbNull 检查值是否为 null

所以你最后的 if 陈述应该是这样的:

if (tenantexportReader.IsDbNull(8))
{
     tenantimportCommand.Parameters["PRICEASK"].Value = "0.00";
} 
else 
{
     tenantimportCommand.Parameters["PRICEFINAL"].Value = tenantexportReader.GetSqlMoney(8).ToDecimal();
}

为什么要将字符串分配给货币值???

可能你想做的是这样的:

var priceFinal = tenantexportReader.GetSqlMoney(8);

tenantimportCommand.Parameters["PRICEFINAL"].Value = (decimal)(priceFinal.IsNull ? 0 : priceFinal);

我真的不明白为什么当它为空时设置为“0.00”(字符串),当它不为空时设置为十进制值。

同样,对于 date/datetime 值,您为什么要使用字符串转换并引发错误?只需将日期作为日期时间传递。