Kevin Kevin - 4 months ago 19
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
that the value returned is
. 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
returned by the query to my
nullable int

Answer Source

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;