Search code examples
c#.net.net-corepostman

"Sequence contains no elements" Error .Net Core 5


There are 2 ids in my database. Both of them avaible in my database. But one of them works normally and the other gives a "Sequence contains no elements" error.

SELECT * FROM Company
where Id ='08db1da9-6bcx' or Id ='08db3387-12as';

This sql gets two of my company. Also "{{base_web_url}}/company/008db1da9-6bcx" this GET Method works fine but "{{base_web_url}}/company/08db3387-12as" gives Sequence contains no elements error.

Here is my code that I've trouble:

var company = await this.mainDbContext.Company
      .Where(x => x.Id == id)
      .Include(x => x.Employees)
      .ThenInclude(x => x.Phones)
      .Include(x => x.Employees)
      .ThenInclude(x => x.Emails)
      .Include(x => x.Logo)
      .ProjectToType<CompanyModel>()
      .FirstOrDefaultAsync()
      .ConfigureAwait(false);

Solution

  • Error - The error is based on you accessing the "this.mainDbContext.Company" collection by using Linq.

    When you go ".Where(x => x.Id == id)" it's actually ".Where(company => company.Id == id)"

    Culprit- The issue is that the "this.mainDbContext.Company" collection is empty so what it's actually doing is

    ".Where(x => empty == id)" so the compiler goes well you have asked me to check where but it can't be a where since the collection you have provided is empty hence the "Sequence contains no elements"

    -Solution If the process should be stopping due to an error while executing you need to sort how you are getting the data flowing in if not as the process needs to silently handle it and continue then you need to handle that or stick a '?'after "this.mainDbContext.Company".