Getting error "Sequence contains no elements"


Hello, I am using the below code to fetch some data from database and getting the error "Sequence contains no elements"

 public static IEnumerable<CompanyLicenseKey> GetCompanyLicenseKey()
{
            OPEntities onepassDB = new OPEntities();

            //Let's get the onepass User model first
            var user = onepassDB.UserAccounts.Where(x => x.Email == OnePassUserAccountEmail).First(); //error in this line

            var userLicenseList = from c in user.CompanyProfiles
                                  join l in onepassDB.CompanyLicenseKeys.Where(x => x.IsDisabled == false)
                                  .Select(x => new { x.CRMID, x.LicenseKey, x.FriendlyName, x.ProductName })
                                  on new { c.CRMID } equals new { l.CRMID }
                                  select new Models.OnePass.CompanyLicenseKey { LicenseKey = l.LicenseKey, FriendlyName = l.FriendlyName, ProductName = l.ProductName };

            if (ProductName == "")
                return userLicenseList.ToList().OrderBy(x => x.FriendlyName);
            else
                return userLicenseList.Where(x => x.ProductName == ProductName).ToList().OrderBy(x => x.FriendlyName);
        }

Error image

sequence-contains-no-element-csharp.png

So how to solve this error? Or handle this error and get rid of it?


Asked by:- jon
0
: 212 At:- 2/23/2018 8:42:37 AM
C# entity-framework asp.net-mvc






2 Answers
profileImage Answered by:- Vinnu

According to error, there is no element in the database of the same name and email id, please debug your code and also try to use .FirstOrDefault() instead of .First(), to avoid errors like this

You can try like this

var user = onepassDB.UserAccounts.Where(x => x.Email == OnePassUserAccountEmail).FirstOrDefault();

if(user != null)
{

 //do something here
}

You can also use .SingleOrDefault() instead of .First(), it also returns null when no element is found

2
At:- 2/23/2018 3:56:32 PM


profileImage Answered by:- jaya

There are some basic rules to handle this error in LINQ or lambda expression

  1. If you are using Single in LINQ, change your habit to use SingleOrDefault.
  2. If you are using First or Last in LINQ, use FirstOrDefault or LastOrDefault.
  3. If you are using ElementAt, use ElementAtOrDefault.
1
At:- 2/26/2018 6:55:30 AM





Login/Register to answer
Or
Register directly by posting answer/details

Full Name *

Email *




By posting your answer you agree on privacy policy & terms of use