Home > CRM 2011 > “Sequence contains no elements” LINQ error – FIX

“Sequence contains no elements” LINQ error – FIX

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

🙂

Advertisement
  1. No comments yet.
  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: