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

The only way I know 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
+3
source share
2 answers

You can assign the LINQ result to a variable and check if .Count ()> 0. This way you won’t have 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
+5
source

Use .FirstOrDefault (). You will get the first record if there is one, or null if there is no record.

+5
source

Source: https://habr.com/ru/post/1709351/


All Articles