views:

539

answers:

1

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?

+1  A: 

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.

Ronald Wildenberg
You're right. I was sure I'd already tried that so I didn't try it. . . So much for my memory! Thanks
Jeff