Dave Mackey
Dave Mackey

Reputation: 4432

Avoid Error when No Results from Entity Query

I have a simple Entity query:

Dim rhcexists = From p In dbContracts.Signatures _
                    Where p.StudentID = people_code_id _
                    And p.ContractType = "rhc" _
                    Order By p.ID Descending _
                    Select p

I then check whether one of the result values is more recent than six months ago using an if..then like so:

If rhcexists.First.SignatureDate > Date.Today.AddMonths(-6) Then
End If

However, if there are no results returned this will return an error. Is there a way for me to tell it to act as if the date is older than six months if there is no value at all? e.g., could I in pseudo do something like:

If Exists(rhcexists.First.SignatureDate, Date.Today.AddMonths(-8)) > Date.Today.AddMonths(-6) Then

End If

Upvotes: 0

Views: 330

Answers (2)

Jon Skeet
Jon Skeet

Reputation: 1499860

You're using the First extension method, which will go bang if there are no results. You could do:

Dim first = rhcexists.FirstOrDefault()
If first IsNot Nothing AndAlso first.SignatureDate > Date.Today.AddMonths(-6) Then
    ' Do stuff here
End If

FirstOrDefault will return Nothing if there are no results, instead of throwing an exception.

Upvotes: 2

Doug Chamberlain
Doug Chamberlain

Reputation: 11341

Use FirstOrDefault instead of First. Then you can setup what default returns

Upvotes: 1

Related Questions