Reputation:
I am parsing two Excel files that contain many fields, most importantly TOTAL_DOLLARS and TOTAL_UNITS fields, that often have values, but some of them are left blank, or null. I want to JOIN
these two DataTables using LINQ where the UPC
fields are equal. However, I have run into the following error:
Cannot cast DBNull.Value to type 'System.Decimal'. Please use a nullable type
This error occurs when I try to join the two tables because of the null fields.
My LINQ code is as follows:
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")}
Upvotes: 0
Views: 5613
Reputation: 24526
Given that WKND_DATE can also be null, get the field as a Nullable(Of DateTime)
(DateTime?
) like so:
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")}
Upvotes: 2