Fixing LINQ Error: Sequence contains no elements
When you get theLINQ Error “Sequence contains no elements”, this is usually because you are using the First() or Single() command rather than FirstOrDefault() and SingleOrDefault(). Take for example the following code that uses First() on the results of the LINQ query. If there are no results, the call to First() triggers the “Sequenc contains no elements” error.: var rel = (from r in relEnds where r.Contains(added.OtherEndKey(entity.EntityKey)) select r).OfType<EntityReference>().First(); To fix the problem, all you have to do is change First() to FirstOrDefault() which returns a null value when there are no results from the select: var rel = (from r … Continue reading Fixing LINQ Error: Sequence contains no elements