有没有一种很好的方法来检测Linq-To-Entities查询中的空结果?
问题描述:
我知道的唯一途径是尴尬:有没有一种很好的方法来检测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
答
您可以将LINQ结果分配给一个变量,并检查.Count()是否> 0。这样您就不需要执行两次相同的查询。
代码:
'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
答
使用.FirstOrDefault()。如果有第一条记录,您将获得第一条记录;如果没有返回记录,则返回null。
+0
感谢。我在一些例子中已经看到了,但从未尝试过。欣赏提示。 – Jeff 2009-05-29 02:16:03
谢谢。 “count”方法不存在于“first”调用中。但是,我试图删除“第一个”,然后在if语句内创建一个新的变量,这只是“第一个”结果。 “dim rr = r.first()”看起来好多了,并将查询保存在一个地方。 – Jeff 2009-05-29 02:10:40