Kevin Kevin - 19 days ago 7
C# Question

Can't set nullable int to LINQ query's return value?

I want to retrieve an Id from a table based on certain criteria. If the criteria isn't met, I just want to return the default value (in this case, I'm assuming null). Here's my code:

int? circuitTypeId = cimsContext.CircuitTypes.FirstOrDefault(ct => ct.Name == circuitType).Id;


I am assuming that if there isn't a match between
ct.Name
and
circuitType
that the value returned is
null
. However, when running my program, I get an error on this line saying "Null reference exception". I know that the record isn't there, but shouldn't I be able to assign the
null
returned by the query to my
nullable int
variable?

Answer

You should first check for null before assigning the circuitTypeId variable:

int? circuitTypeId;

var circuitType = cimsContext.CircuitTypes.FirstOrDefault(ct => ct.Name == circuitType);
if(circuitType != null)
{
    circuitTypeId = circuitType.Id;
}