Jeff
Jeff

Reputation: 8138

Is there a good way to detect empty results in a Linq-To-Entities query?

The only way I know of is awkward:

'check for empty return
Dim count As Integer = (From s In myEntity.employee Where employeeID = myEmployeeIDVariable).Count

'If there is a record, then process
If count > 0 Then
     Dim r = (From s In myEntity.employee Where employeeID = myEmployeeIDVariable).First()

     . . . do stuff . . .
End If

Upvotes: 3

Views: 9275

Answers (2)

Adrian Godong
Adrian Godong

Reputation: 8911

You can assign LINQ result to a variable and check if .Count() is > 0. That way you will not need to do the same query twice.

Code:

'check for empty return
Dim r = (From s In myEntity.employee Where employeeID = myEmployeeIDVariable)

'If there is a record, then process
If r.Count() > 0 Then
  . . . do stuff . . .
End If

Upvotes: 6

Jonathan Rupp
Jonathan Rupp

Reputation: 15762

Use .FirstOrDefault(). You'll get the first record if there is one, or null if there isn't a record returned.

Upvotes: 6

Related Questions