Archive

Archive for October 16, 2012

“Sequence contains no elements” LINQ error – FIX

October 16, 2012 Leave a comment

I was getting below error while querying “AccountSet” using LINQ in my plug-in

System.InvalidOperationException: Sequence contains no elements

Reason:-

  • Exception raised when there were no records that matches to the criteria specified in my LINQ query
  • I had my query statement as below

  var account = orgContext.accountSet.Where(acct => (acct.name == “Rajeev”)).First();

  • There were no ‘Accounts’ with name=Rajeev and using of First() resulted “Sequence contains no elements” exception

Fix:-

  • Replace the method First() with FirstOrDefault().
  • The method FirstOrDefault() returns a null value, if there are no records that matches to the filtering criteria
  • Now my LINQ expression looks as below

  var account = orgContext.accountSet.Where(acct => (acct.name == “Rajeev”)). FirstOrDefault();

🙂