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?
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;
尝试这个 :
int? circuitTypeId = cimsContext.CircuitTypes.Where(ct => ct.Name == circuitType).Select(p => p.Id).FirstOrDefault();
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;
}
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);
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;
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.