Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sequence contains no elements with LINQ FirstOrDefault

Tags:

c#

.net

linq

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?

like image 588
jaffa Avatar asked May 09 '26 08:05

jaffa


2 Answers

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;
like image 126
marc_s Avatar answered May 10 '26 22:05

marc_s


You do realize that you're trying to invoke the "location_key" property on an object that potentially is going to be NULL, right?

like image 26
Rich Avatar answered May 10 '26 23:05

Rich



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!