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.
Rahul
Quote of the day:
Few people can see genius in someone who has offended them. - Robertson Davies