0

我正在解析两个 Excel 文件,其中包含许多字段,最重要的是 TOTAL_DOLLARS 和 TOTAL_UNITS 字段,它们通常具有值,但其中一些是空白或空值。我想在字段相等JOIN的情况下使用 LINQ 来处理这两个 DataTables 。UPC但是,我遇到了以下错误:

Cannot cast DBNull.Value to type 'System.Decimal'. Please use a nullable type

由于空字段,当我尝试加入两个表时会发生此错误。

我的 LINQ 代码如下:

Dim query = From c In dtDollars.AsEnumerable() _
      Join r In dtUnits.AsEnumerable() _
      On c.Field(Of String)("UPC") Equals r.Field(Of String)("UPC") _
      Select _
      New _
      With {.UPC = r.Field(Of String)("UPC"), .WIC_NUMBER = c.Field(Of String)("WIC_NUMBER"), _
      .WAG_ITEM_DESC = c.Field(Of String)("WAG_ITEM_DESC"), _
      .WAG_BRAND = c.Field(Of String)("WAG_BRAND"), .UOM = c.Field(Of String)("UOM"), _
      .GSK_PROMO_GRP = c.Field(Of String)("GSK_PROMO_GRP"), _
      .TOTAL_DOLLARS = c.Field(Of Decimal)("TOTAL_DOLLARS"), _
      .TOTAL_UNITS = r.Field(Of Integer)("TOTAL_UNITS"), _
      .WKND_DATE = c.Field(Of DateTime)("WKND_DATE")}
4

1 回答 1

2

鉴于 WKND_DATE 也可以为空,将字段作为Nullable(Of DateTime)( DateTime?) 获取,如下所示:

Dim query = From c In dtDollars.AsEnumerable() _
   Join r In dtUnits.AsEnumerable() _
   On c.Field(Of String)("UPC") Equals r.Field(Of String)("UPC") _
   Select _
   New _
   With {.UPC = r.Field(Of String)("UPC"), .WIC_NUMBER = c.Field(Of String)("WIC_NUMBER"), _
   .WAG_ITEM_DESC = c.Field(Of String)("WAG_ITEM_DESC"), _
   .WAG_BRAND = c.Field(Of String)("WAG_BRAND"), .UOM = c.Field(Of String)("UOM"), _
   .GSK_PROMO_GRP = c.Field(Of String)("GSK_PROMO_GRP"), _
   .TOTAL_DOLLARS = c.Field(Of Decimal?)("TOTAL_DOLLARS"), _
   .TOTAL_UNITS = r.Field(Of Integer?)("TOTAL_UNITS"), _
   .WKND_DATE = c.Field(Of DateTime?)("WKND_DATE")}
于 2012-12-21T19:17:17.780 回答