Kevin
Kevin

Reputation: 4848

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?

Upvotes: 3

Views: 7142

Answers (5)

Carter Medlin
Carter Medlin

Reputation: 12495

In C# version 6 you can simply add a ? before id to prevent the properties of null objects from being referenced.

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

Upvotes: 3

Amol Bavannavar
Amol Bavannavar

Reputation: 2072

Try this :

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

Upvotes: 3

Rahul Singh
Rahul Singh

Reputation: 21825

Your assumption is wrong, as per your query:-

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

This will return int, when match is found but it will throw a Null Reference Exception when no name matches with that of circuitType. you should do this:-

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

Upvotes: 5

AaronLS
AaronLS

Reputation: 38392

The problem is .Id is probably trying to reference a null CirctuitType.

var circuitType = cimsContext.CircuitTypes.FirstOrDefault(ct => ct.Name == circuitType);
int? circuitTypeId = circuitType.Id; // if circuitType is null, a null reference exception is thrown

Instead, you'll need to test the reference for null:

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

Upvotes: 1

krivtom
krivtom

Reputation: 24916

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;
}

Upvotes: 2

Related Questions