James Oshomah
James Oshomah

Reputation: 224

Handling Null Date in an Entity Framework query

Please am pulling some data from the database using linq to entities.From the query result i make a collection and bind to a gridview control.Problem is on one of the date column from the database some of the values are null and when i do a tostring it gives me an exception. Below is the first query i used to get the data ferom the database.

    Dim sSession = From ses In DemoSchool.Terms
                   Select New With {Key .Session = ses.Session,
                                    Key .Term = ses.Term1,
                                    Key .StartDate = ses.StartDate,
                                    Key .EndDate = ses.EndDate,
                                    Key .NextTerm = ses.NextTerm}

Then from this result i do a select to get the columns so that i can apply formating to the datetime column

  Dim query = (From estty In sSession Select estty).ToList() _
              .Select(Function(essty) New With {.Session = essty.Session,
                                 .Term = essty.Term,
                                 .StartDate = essty.StartDate.ToString("ddd d MMM yyyy"),
                                 .EndDate = CDate(essty.EndDate).ToString("ddd d MMM yyyy"),
                                 .NextTerm = CDate(essty.NextTerm).ToString("ddd d MMM yyyy")})

the problem comes from the last two statement because this column in the database contains null values and i thought CDate method was going to work but it turns out i was wrong. (This is where the error is being thrown) .EndDate = CDate(essty.EndDate).ToString("ddd d MMM yyyy"), .NextTerm = CDate(essty.NextTerm).ToString("ddd d MMM yyyy")})

The second query result is bounded to a gridview like so grdShowSession.DataSource = query grdShowSession.DataBind() The error shown is Nullable object must have a value. Please i need help.

Upvotes: 1

Views: 603

Answers (1)

Alexandre
Alexandre

Reputation: 498

Yo could make a function that returns a string with the element like

Function returnElementString As String(element As Objec)
    If IsNothing(element) Then
       return "whatever"
    Else 
       return CDate(element).ToString("ddd d MMM yyyy")
    End If
End Function

and in you code you'll use as example:

.EndDate = returnElementString(essty.EndDate)

Upvotes: 0

Related Questions