You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

VB.NET Linq中FX_RATE空值转0遇System.Decimal类型转换错误求助

问题解决:DBNull转Decimal类型错误

错误原因

你当前写法里,tl_ancDT.Field(Of Decimal)("FX_RATE")会直接尝试把DBNull.Value转换为非可空的Decimal类型,这一步在IsDBNull判断之前就会触发转换错误——因为非可空Decimal无法接受DBNull值。

解决方案

改用**可空Decimal类型(Decimal?)**读取字段,再处理空值:

方法1:用HasValue判断替换

修改FX_RATE对应的代码行:

Key .FX_RATE = If(tl_ancDT.Field(Of Decimal?)("FX_RATE").HasValue, tl_ancDT.Field(Of Decimal?)("FX_RATE").Value, 0D)

方法2:用GetValueOrDefault简化写法

更简洁的版本,直接利用可空类型的GetValueOrDefault方法设置默认值:

Key .FX_RATE = tl_ancDT.Field(Of Decimal?)("FX_RATE").GetValueOrDefault(0D)

修改后的完整代码

Dim query =
From tl_ancDT In dtReportData.AsEnumerable
Group Join tl_prcDT In dtPostedFlag.AsEnumerable On tl_ancDT.Field(Of String)("ENTITY") Equals tl_prcDT.Field(Of String)("ENTITY") And
tl_ancDT.Field(Of String)("ACCOUNT") Equals tl_prcDT.Field(Of String)("ACCOUNT") And
tl_ancDT.Field(Of String)("TRANSACTION_BATCH_ID") Equals tl_prcDT.Field(Of String)("TRANSACTION_BATCH_ID")
Into tl_ancDT_tl_prcDT = Group 
From tl_prcDT In tl_ancDT_tl_prcDT.DefaultIfEmpty() 
Select New With {
    Key .ENTITY = tl_ancDT.Field(Of String)("ENTITY"),
    Key .ACCOUNT = tl_ancDT.Field(Of String)("ACCOUNT"),
    Key .STATUS = tl_ancDT.Field(Of String)("STATUS"),
    Key .ACTIVITY_NUMBER = tl_ancDT.Field(Of String)("ACTIVITY_NUMBER"),
    Key .TRANSACTION_BATCH_ID = tl_ancDT.Field(Of String)("TRANSACTION_BATCH_ID"),
    Key .ENTERED_CURRENCY = tl_ancDT.Field(Of String)("ENTERED_CURRENCY"),
    Key .OPENING_BALANCE = tl_ancDT.Field(Of Decimal)("OPENING_BALANCE"),
    Key .FX_RATE = tl_ancDT.Field(Of Decimal?)("FX_RATE").GetValueOrDefault(0D),
    Key .CLOSING_BALANCE = tl_ancDT.Field(Of Decimal)("CLOSING_BALANCE"),
    Key .POSTEDFLAG = If(tl_prcDT Is Nothing,String.Empty , tl_prcDT.Field(Of String)("POSTEDFLAG"))
}

原理说明

Field(Of Decimal?)会将字段值读取为可空Decimal类型:

  • 字段有有效值时,返回包含该值的Decimal?实例,HasValue为True
  • 字段是DBNull时,返回Nothing,HasValue为False
    通过GetValueOrDefault(0D)可以直接将空值替换为0,同时保留正常的Decimal值,彻底避免转换错误。

内容的提问来源于stack exchange,提问作者user1492218

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.01 21:11:06