使用Any()检查行返回VB.NET中的错误

时间:2012-04-12 14:44:45

标签: asp.net vb.net entity-framework entity-framework-4

我有以下功能:

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

但是它正在烦恼中.Any()说,“输入字符串的格式不正确。”有什么想法吗?这是返回行的集合,就像我在其他地方使用相同的代码而没有问题?

3 个答案:

答案 0 :(得分: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

答案 1 :(得分:1)

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

从你得到的错误中我猜它是p.room =“”就是这样,p.room是一个字符串值?如果不是那么检查所有其他条款,它们都是字符串吗?那一年看起来不太可能,特别是存储为字符串。

答案 2 :(得分:0)

尝试查询

p.room = ''

而不是

p.room = ""