应对 Linq-To-Entities Entity SQL 中的 ObjectQuery 单一枚举挑战

发布于 2024-07-21 21:30:29 字数 752 浏览 7 评论 0原文

我正在修改这个示例:

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

情话已封尘 2024-07-28 21:30:29

如果您在查询末尾添加 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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文