3

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?

Kevin
  • 4,798
  • 19
  • 73
  • 120
  • 3
    No, at the moment you'll need to explicitly check for null before dereferencing Id. Or you can wait for [Roslyn's Elvis](http://stackoverflow.com/q/27493541/314291) operator `?.` :) – StuartLC Jan 05 '15 at 05:37
  • 2
    `FirstOrDefault` is worthless in this situation because you're trying to access `Id` from potentially `null`. `First` would at least throw a better exception. – jamesSampica Jan 05 '15 at 05:38

5 Answers5

5

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;
Rahul Singh
  • 21,585
  • 6
  • 41
  • 56
3

Try this :

int? circuitTypeId = cimsContext.CircuitTypes.Where(ct => ct.Name == circuitType).Select(p => p.Id).FirstOrDefault();
Amol Bavannavar
  • 2,062
  • 2
  • 15
  • 36
3

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;
Carter Medlin
  • 11,857
  • 5
  • 62
  • 68
2

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;
}
dotnetom
  • 24,551
  • 9
  • 51
  • 54
1

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);
AaronLS
  • 37,329
  • 20
  • 143
  • 202