应对 Linq-To-Entities Entity SQL 中的 ObjectQuery 单一枚举挑战
我正在修改这个示例:
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 进行编号只有一次。 (随后的枚举尝试会抛出异常。)枚举发生在 foreach 语句中。 问题是,如果查询为空,尝试 For Each 将引发异常。 但如果我检查计数:
If productQuery1.Count > 0 Then . . .
那就耗尽了我一次计数的机会。 我可以将 For Each 嵌套在 try/catch 块中并丢弃空查询异常,但这很丑陋。 有更好的解决方案吗?
I'm working on modifying this example:
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
An ObjectQuery can be enumberated only once. (Subsequent attempts at enumeration throw an exception.) The enumberation takes place in the for each statement. The problem is that if the query is empty attempting a For Each will throw an exception. But if I check for a count:
If productQuery1.Count > 0 Then . . .
That eats up my one chance at enumeration. I could nest the For Each in a try/catch block and throw away the empty query exceptions, but that's ugly. Is there a better solution?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
如果您在查询末尾添加
ToList()
调用,您应该能够根据需要随时枚举结果。If you add a
ToList()
call to the end of your query, you should be able to enumerate the results as often as you like.