Friday, May 14, 2010

Fixing LINQ Error “Sequence contains no elements”

Problem
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();


ServiceSummaryType serviceSummary = (ServiceSummaryType)responseItems.ServiceSummary.Where(a => a.Service.Code == objAvailableServicesAndRates.ServiceId_ServiceTypeCode.Split('#')[0]).First();

Solution
To Solve this problem replace the method single() with SingleOrDefault() method and First() with FirstOrDefault(). the methods SingleOrDefault() and FirstOrDefault returns a null value if there are no source records that matches to the filtering criteria.

1 comment: