James Ray Anderson

James Ray Anderson
James Ray Anderson
0 comments

Sequence Contains No Elements (C#)

1:46 PM
This error happens when trying to LINQ for retrieving an item from a table but there are no items.  For example:
PrimaryContext myContext = new PrimaryContext();EmailModel emailAccount = myContext.EmailModel.Where(x => x.Email == "someone@someone.com").First();

If there are no items to retrieve into the declared emailAccount you will receive an InvalidOperationException with details of "Sequence contains no elements".

To resolve this, use .FirstOrDefault() instead of .First().  This will give you the actual model or null if the condition is not found.

EmailModel emailAccount = myContext.EmailModel.Where(x => x.Email == "someone@someone.com").FirstOrDefault();

0 comments:

 
Toggle Footer
Top