C# – Sequence contains no elements with LINQ FirstOrDefault

clinqnet

I'm getting 'Sequence contains no elements' with LINQ FirstOrDefault.

int? locationId = _ctx.m_locations.FirstOrDefault(
                       l => l.name.ToLower() == countyOrTown.ToLower()
                  ).location_key;

I thought the whole point of FirstOrDefault is that it doesn't raise an exception if there are no entries in the database and just returns null?

Best Answer

Since as you say yourself, .FirstOrDefault() will return a NULL value, you need to first check for that NULL and only if it's NOT NULL then access it's .location_key property:

int? locationId = null;

var firstOrDefault = _ctx.m_locations.FirstOrDefault(l => l.name.ToLower() == countyOrTown.ToLower());

if(firstOrDefault != null)
    locationId = firstOrDefault.location_key;