2012-04-12 82 views
1
檢查行

我有以下功能:使用任何()返回錯誤VB.NET

Public Function CheckHasRoom(people_id As String, semester As String, year As String) 
    ' Don't let folks already registered for a room register for another. 
    Dim RoomSelected As String 
    Using dbContext As pbu_housingEntities = New pbu_housingEntities 
     Dim hasroom = (From p In dbContext.Residents _ 
         Where p.people_code_id = people_id _ 
         Where p.semester = semester _ 
         Where p.year = year _ 
         Where (p.room = "" _ 
         Or p.building Is Nothing) _ 
         Select p) 
     If hasroom.Any() Then 
      ' Let them keep going. 
      RoomSelected = "N" 
     Else 
      ' Redirect them to the main page. 
      RoomSelected = "Y" 
      ' HttpContext.Current.Response.Redirect("default.aspx") 
     End If 
    End Using 
    Return RoomSelected 
End Function 

但它在hasroom.Any()竊聽出來說:「輸入字符串的不正確格式。」任何想法爲什麼?這是返回的行集合,就像我在其他地方使用相同的代碼而沒有問題?

+3

您是否考慮過逐步測試Linq查詢?每次在每行添加一行,看看是否有錯誤。 – JurgenStillaert 2012-04-12 14:49:30

回答

1

由於DaveMackay建議在他的評論就我看來像WHERE子句中的一個導致錯誤。在代碼的.Any()點出現錯誤的原因是,這是查詢實際執行的位置,直到您聲明瞭查詢的意圖,但實際上還沒有發生。如果將查詢包裝在括號中並添加.ToList()結尾,則可能會在聲明查詢的行上發生en錯誤,因爲這會強制立即執行。

從你得到的錯誤我猜這是p.room =「」這是做的,是p.room一個字符串值?如果不是那麼檢查所有其他的子句,它們都是字符串嗎?那年我看起來不太可能,尤其是將它存儲爲一個字符串。

2

.Count中嘗試查詢,而不是嘗試使用

Dim hasroom = (From p In dbContext.Residents _ 
        Where p.people_code_id = people_id _ 
        AndAlso p.semester = semester _ 
        AndAlso p.year = year _ 
        AndAlso (p.room = "" _ 
        Or p.building Is Nothing) _ 
        Select p).count 

'-------- Example -------- 

Public Sub test() 

    Dim l1 As New List(Of String) From {"1", "2", "3"} 
    Dim l2 As New List(Of String) From {"1", "2", "3", "4", "5"} 

    'return nothing 
    Dim noresult = From p In l1 Where 1 = 0 Select p 

    'return ienumerable 
    Dim someresult = From p In l1 Where p > 2 Select p 

    'return ienumerable with count = 1 with handled_noresult(0)=Nothing 
    Dim handled_noresult = (From p In l1 Where 1 = 0 Select p).DefaultIfEmpty 

    'return emtpty array with .Length=0 --try this 
    Dim handled_noresult2 = (From p In l1 Where 1 = 0 Select p).ToArray 

    'return 1 
    Dim FakeNoResult1 = handled_noresult.Count() 

    'return 0 
    Dim FakeNoResult2 = handled_noresult2.Count() 

End Sub 
+0

我得到錯誤「InvalidCastException未被用戶代碼處理」和「從字符串轉換」「類型'雙'無效。」 – davemackey 2012-04-12 16:15:46

0

p.room = '' 

p.room = ""