1

我有以下功能:

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() 上出现了问题,说“输入字符串的格式不正确。” 关于为什么的任何想法?这会返回一组行,就像我在其他地方使用相同的代码没有问题一样?

4

3 回答 3

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
于 2012-04-12T15:27:37.040 回答
1

正如 DaveMackay 在他的评论中所建议的那样,在我看来,其中一个 where 子句导致了错误。它在代码的 .Any() 点出错的原因是,这是实际执行查询的地方,直到那时您已经声明了查询的意图,但它实际上还没有发生。如果您将查询包装在括号中并在其末尾添加 .ToList() ,您可能会在声明查询的行上出现错误,因为这将强制立即执行。

From the error you got I'd guess it's the p.room = "" that is doing it, is p.room a string value? If it's not that then check all the other clauses, are they all strings? It looks unlikely to me that year especially would be stored as a string.

于 2012-04-13T08:28:01.020 回答
0

尝试查询

p.room = ''

代替

p.room = ""
于 2012-04-13T04:05:03.000 回答