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?
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;
You do realize that you're trying to invoke the "location_key" property on an object that potentially is going to be NULL, right?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With