“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();
🙂
Categories: CRM 2011
CRM 2011, FirstOrDefault, Linq, Sequence contains no elements
Comments (0)
Trackbacks (0)
Leave a comment
Trackback