Reputation: 130
I'm trying to execute a query that has a number of left joins, as one of the foreign key columns is nullable, and when Dapper finds a record in which that particular column is nullable, a NullReferenceException is thrown when the mapper tries to put the result together. I'm using 'Id' as my PK column and haven't had an issue with any of the other tables, but I'm not quite sure the best way to work around this one.
I need to be able to return a set of results in which some of the fields (and related records) may be null, and others may not be null.. is there a way to get around this without having two separate queries?
here's part of the query.. ani.DeviceMacAddress is the nullable FK.
(query,
(ani, adm, d, ma, sma, n, i, sni) =>
{
ani.DeviceMacAddress = adm;
adm.Device = d; // Throws NullReferenceException here
adm.MacAddress = ma;
ani.NetworkV4 = n;
ani.IpAddressV4 = i;
ani.Status = sni;
ma.Status = sma;
return ani;
},
Upvotes: 1
Views: 805
Reputation: 1063714
I'm guessing adm
is null, from the location. So... check for that:
ani.DeviceMacAddress = adm;
if(adm != null) {
adm.Device = d;
adm.MacAddress = ma;
}
ani.NetworkV4 = n;
ani.IpAddressV4 = i;
ani.Status = sni;
if(ma != null) {
ma.Status = sma;
}
return ani;
Upvotes: 1