Sequence contains no elements


Select

Image via Wikipedia

The error occurs when you try to access an object returned by a Linq query with 0 elements in the result set an
InvalidOperationException is thrown. Below is a simulation to generate the error:

Dim productQuery = From p In context.Products Where p.ID = -1 Select p

Dim p As Product = productQuery.Single()

An exception is thrown by the Single() method because the productQuery object has no products inside and the Single() method is
trying to reach the first entity in the productQuery.

To avoid this problem, we must check whether productQuery is containing some items or not. Here is the correct way to do it:

                                    Dim productQuery = From p In context.Products Where p.ID = -1 Select p 
                                    If productQuery.Count > 0 Then
                                            Dim p As Product = productQuery.Single()
                                    Else
                                            Return Nothing
                                    End If

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: