2016-07-27 112 views
0

美好的一天,LINQ查詢在VB

我查詢使用LINQ我的數據庫,我遇到了一個問題,查詢搜索的搜索短語的列和基於如果列有這句話,它隨後返回結果,查詢是下面,

Dim pdb = New ProductDataContext()    
    Dim query = 
     From a In pdb.tblUSSeries 
     Join b In pdb.tblSizes_ On a.Series Equals b.Series 
     Where 
     a.Series.ToString().Equals(searchString) Or            
     b.Description.Contains(searchString) Or Not b.Description.Contains(Nothing) 
     Order By b.Series, b.OrderCode Ascending 
     Select New CustomSearch With 
      { 
       .Series = a.Series, 
       .SeriesDescription= a.Description, 
       .Coolant = a.Coolant, 
       .Material = a.Material, 
       .Standard = a.Standard, 
       .Surface = a.Surface, 
       .Type = a.Type, 
       .PointAngle = a.PointAngle, 
       .DiaRange = a.DiaRange, 
       .Shank = b.Shank, 
       .Flutes = b.Flutes, 
       .EDPNum = b.EDPNum, 
       .SizesDescription = b.Description, 
       .OrderCode = b.OrderCode        
      }    
    Return query 

我認爲問題是,表中的某些行是空的,所以當它正在檢查短語列,當它遇到的行爲null, ,打破並返回此錯誤,

由於物化值爲空,所以強制類型爲「System.Int32」的類型轉換失敗。結果類型的泛型參數或查詢都必須使用可爲空的類型。

我已經運行此查詢對所有填充了數據的行的另一列,它會返回結果ok。

所以我的問題是,如何在VB中使用提供的searchstring查詢數據庫並在列中的某些行具有空值時返回結果。

任何幫助將是偉大的。

回答

1

當你發生異常的投影(即選擇新CustomSearch) 是的你試圖null分配給一些整型屬性 (不知道,你的屬性之一即是)

2點的選擇之一:

1)使用nullalbe類型爲您的屬性(或只是一個屬性)。

2)項目與內聯如果(??在C#中),我不知道VB,所以不要聽我的語法。

以系列只是作爲一個例子,我不知道,如果它是一個int或如果這是有問題的物業

Select New CustomSearch With 
     { 
      .Series = If(a.Series Is Nothing,0, CInt(a.Series)) 
     } 

    In C# 

    Select new CustomSearch 
     { 
      Series = a.Series ?? 0; 
     }