Site icon Tech Dreams

Fixing LINQ Error “Sequence contains no elements” [C#, LINQ]

Problem

When you query a LINQ data source with the Single() method call you may get the exception “System.InvalidOperationException: Sequence contains no elements”.

Cause

This exception is raised when there are no records that matches to the criteria specified in the LINQ query. For example the following LINQ query raises the exception if the where criteria does not match with any records in the data source

var objResultObject = (from RfVal in db.t_reference_values
                    where RfVal.id == plRefValId
                    select new { RfVal.description }).Single();

Solution

To solve the problem replace the method Single() call with SingleOrDefault() method. The method SingleOrDefault() returns a null value if there are no source records that matches to the filtering criteria.

var objResultObject = (from RfVal in db.t_reference_values
                    where RfVal.id == plRefValId
                    select new { RfVal.description }).SingleOrDefault();

Exit mobile version