none
Query Result and DefaultIfEmpty RRS feed

  • Question

  • I'm trying to understand how to use DefaultIfEmpty.

     

    I created an example using a simple result structure..

     

    Structure sRes
        Dim forename As String
        Dim surname As String
    End Structure

     

    Then tried the following code..

     

    Dim DC As New DBdc
    Dim Res As IQueryable(Of sRes)
    Try
        Dim DefRes As New sRes With {.forename = "Empty", _

                                     .surname = "Empty"}
        Res = (From i In DC.PERSON _
              Where i.person_ref = "rubbish key" _
             Select New sRes With {.forename = i.forename1, _
                                   .surname = i.surname}).DefaultIfEmpty(DefRes)

    Catch ex As Exception
        Throw New Exception(ex.Message)
    End Try

    For Each Rec In Res
        Console.Write("Forename=" & Rec.forename & " Surname=" & Rec.surname)
    Next

     

    This throws an exception of: Unsupported overload used for query operator 'DefaultIfEmpty'

     

    I've tried it using a much simpler version too, with exacly the same result..

     

    Dim DC As New DBdc
    Dim Str As String
    Try
        Str = (From i In DC.PERSON _
              Where i.person_ref = "rubbish key" _
             Select i.surname).DefaultIfEmpty("Empty").Single
    Catch ex As Exception
        Throw New Exception(ex.Message)
    End Try
    Console.Write("Surname=" & Str)

     

    How on earth do you use DefaultIfEmpty ?

     

    Monday, October 27, 2008 6:13 PM

Answers

  • The only 'default' that L2S supports in translation to SQL is the default default (null/nothing).  You get this default default by using the overload of DefaultIfEmpty that has no argument.

     

    Monday, October 27, 2008 10:05 PM
    Moderator

All replies

  • The only 'default' that L2S supports in translation to SQL is the default default (null/nothing).  You get this default default by using the overload of DefaultIfEmpty that has no argument.

     

    Monday, October 27, 2008 10:05 PM
    Moderator
  • ok thanks, I just changed the test code to use a list instead.. which seems to work ok.

     

    Dim Res As list(Of sRes)
    Try
        Res = (From i In DC.PERSON _
              Where i.person_ref = "rubbish key" _
             Select New sRes With {.forename = i.forename1, _
                                   .surname = i.surname}).ToList
        If Res.Count = 0 Then
            Res.Add(New sRes With {.forename = "Empty", _
                                   .surname = "Empty"})
        End If
    Catch ex As Exception
        Throw New Exception(ex.Message)
    End Try

    For Each Rec In Res
        Console.Write("Forname=" * Rec.forename & " Surname=" & Rec.surname)
    Next

    Monday, October 27, 2008 10:47 PM