System.InvalidOperationException: Sequence contains no elements

by rahul 3/26/2009 1:44:00 AM

While using LINQ, let’s say you decide to do something similar to the following…

    NorthWindDataContext dc = new NorthWindDataContext();
    Product p = dc.Products.First(p1 => p1.ProductName.StartsWith("My New Product"));
    if (p == null)
        return;

    dc.Products.DeleteOnSubmit(p);
    dc.SubmitChanges();
    ShowProducts();

Everything would be fine if you do have a product whose name starts with “My New Product”, but what do you think would happen if that’s not the case? Well surprisingly... you would get an un-handled runtime exception!!!

Exception Details: System.InvalidOperationException: Sequence contains no elements
Source Error:

Line 69:         NorthWindDataContext dc = new NorthWindDataContext();
Line 70: 
Line 71:         Product p = dc.Products.First(p1 => p1.ProductName.StartsWith("My New Product"));
Line 72:         if (p == null)
Line 73:             return;

To get rid of this error, instead of using dc.Products.First, use dc.Products.FirstOrDefault and you should be good!

Happy Coding. Wave
Rahul

 


Quote of the day:
Few people can see genius in someone who has offended them. - Robertson Davies


blog comments powered by Disqus

Search


Tags



Categories

Calendar

<<  March 2010  >>
MoTuWeThFrSaSu
22232425262728
1234567
891011121314
15161718192021
22232425262728
2930311234

View posts in large calendar

All Items
Sign in

Disclaimer

The opinions expressed herein are my own personal opinions and do not represent my employer's view in any way.
© Copyright 2010, Rahul Soni

Powered by BlogEngine.NET 1.4.5.0