有没有一种很好的方法来检测Linq-To-Entities查询中的空结果?

时间:2009-05-29 01:45:30

标签: .net vb.net linq linq-to-entities

我所知道的唯一方法就是尴尬:

'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

2 个答案:

答案 0 :(得分:5)

使用.FirstOrDefault()。如果有第一条记录,您将获得第一条记录,如果没有返回记录,则返回null。

答案 1 :(得分:5)

您可以将LINQ结果分配给变量并检查.Count()是否为>这样你就不需要两次做同样的查询了。

代码:

'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