我正在修改这个例子:
Using advWorksContext As New AdventureWorksEntities
' Call the constructor that takes a command string and ObjectContext.
Dim productQuery1 As New ObjectQuery(Of Product)("Product", advWorksContext)
Dim result As Product
For Each result In productQuery1
Console.WriteLine("Product Name: {0}", result.Name)
Next
End Using
一个 ObjectQuery 只能被枚举一次。(随后的枚举尝试会引发异常。)枚举发生在 for each 语句中。问题是,如果查询为空,则尝试 For Each 将引发异常。但是,如果我检查计数:
If productQuery1.Count > 0 Then . . .
这耗尽了我列举的一次机会。我可以将 For Each 嵌套在 try/catch 块中并丢弃空查询异常,但这很难看。有更好的解决方案吗?