LINQ-Join tables on nullable columns

瘦欲@ 提交于 2019-12-10 17:26:53

问题


how to JOIN tables on nullable columns?

I have following LINQ-query, RMA.fiCharge can be NULL:

Dim query = From charge In Services.dsERP.ERP_Charge _
                     Join rma In Services.dsRMA.RMA _
                     On charge.idCharge Equals rma.fiCharge _
                     Where rma.IMEI = imei
               Select charge.idCharge

I get a "Conversion from type 'DBNull' to type 'Integer' is not valid" in query.ToArray():

Dim filter = _
       String.Format(Services.dsERP.ERP_Charge.idChargeColumn.ColumnName & " IN({0})", String.Join(",", query.ToArray))

So i could append a WHERE RMA.fiCharge IS NOT NULL in the query. But how to do that in LINQ or is there another option?

Thank you in advance.


Solution:

The problem was that the DataSet does not support Nullable-Types but generates an InvalidCastException if you query any NULL-Values on an integer-column(thanks Martinho). The modified LINQ-query from dahlbyk works with little modification. The DataSet generates a boolean-property for every column with AllowDbNull=True, in this case IsfiChargeNull.

Dim query = From charge In Services.dsERP.ERP_Charge _
            Join rma In (From rma In Services.dsRMA.RMA _
                         Where Not rma.IsfiChargeNull
                         Select rma)
              On charge.idCharge Equals rma.fiCharge _
            Where rma.IMEI = imei
            Select charge.idCharge

回答1:


Have you tried adding the null check to your where clause?

Dim query = From charge In Services.dsERP.ERP_Charge _
            Join rma In Services.dsRMA.RMA _
              On charge.idCharge Equals rma.fiCharge _
            Where rma.fiCharge <> Nothing AndAlso rma.IMEI = imei
            Select charge.idCharge

If that doesn't work, you could try something like this:

Dim query = From charge In Services.dsERP.ERP_Charge _
            Join rma In (From rma in Services.dsRMA.RMA _
                         Where rma.fiCharge IsNot Nothing
                         Select rma)
              On charge.idCharge Equals rma.fiCharge _
            Where rma.IMEI = imei
            Select charge.idCharge



回答2:


While you can use LINQ to Datasets to solve this issue, you might find better performance using the predefined DataRelations instead of ad-hoc joins. See http://msdn.microsoft.com/en-us/library/dbwcse3d.aspx for information about data relations.

If you do use LINQ to Datasets, you might want to check out our free bonus chapter 14 on them at http://www.manning.com/marguerie/.



来源:https://stackoverflow.com/questions/5696888/linq-join-tables-on-nullable-columns

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!