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 aNULL
value, you need to first check for that NULL and only if it'sNOT NULL
then access it's.location_key
property: