【问题标题】:Working with the ObjectQuery Single Enumeration Challenge in Linq-To-Entities Entity SQL在 Linq-To-Entities 实体 SQL 中处理 ObjectQuery 单枚举挑战
【发布时间】:2010-10-29 18:34:32
【问题描述】:

我正在修改this 示例:

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 块中并丢弃空查询异常,但这很难看。有没有更好的解决方案?

【问题讨论】:

    标签: vb.net linq-to-entities enumeration entity-sql objectquery


    【解决方案1】:

    如果您在查询末尾添加ToList() 调用,您应该能够根据需要多次枚举结果。

    【讨论】:

    • 你是对的。我确定我已经尝试过了,所以我没有尝试。 . .这么多我的记忆!谢谢
    猜你喜欢
    • 2023-01-18
    • 1970-01-01
    • 2011-04-08
    • 2011-07-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-08-03
    相关资源
    最近更新 更多