views:

632

answers:

2

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
+4  A: 

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

Jonathan
Thanks. I've seen that in some examples, but never tried it out. Appreciate the tip.
Jeff
+2  A: 

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
Adrian Godong
Thanks. The "count" method doesn't exist in a "first" call. But, I tried removing "first" and then inside the if statement created a new variable that is just the "first" result. "dim rr = r.first()" Looks a lot better and keeps the query in one place.
Jeff
Just be aware, if you call .Count() and .First() on the same query, it may result in two hits to the database (Linq-to-Objects would evaluate the query twice, but I don't know about Linq-to-Entities or Linq-to-SQL).
Jonathan
Ah yes, that would be my error when copying and pasting your original code.
Adrian Godong