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
So how to solve this error? Or handle this error and get rid of it?
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.
This can also be caused by the following commands:
So similarly, try to use SingleOrDefaultAsync() instead of FirstAsync().
There are some basic rules to handle this error in LINQ or lambda expression
You can also use DefaultIfEmpty()
before using Single()
or
First()
, to avoid error "sequence contains no elements" as it will ensure, there is an item in the sequence.
var user = onepassDB.UserAccounts.Where(x => x.Email == OnePassUserAccountEmail).DefaultIfEmpty().First();
Thanks.
Subscribe to our weekly Newsletter & Keep getting latest article/questions in your inbox weekly