Reputation: 143
I have two tables which i want to link via left outer join
. Why the below query is returning me this error?
"linq query object reference not set to an instance of an object"
IEnumerable<RoadTrafficCount> roadTrafficCounts =
_unitOfWork.RoadTrafficCountRepository
.Get(i => i.ThanaID == thanaid && i.RoadID == roadid, includeProperties: "VehicleList, VehicleList.VehicleType");
IEnumerable<VehicleList> vehicleLists = _unitOfWork.VehicleListRepository.Get();
var q = (from pd in vehicleLists
join od in roadTrafficCounts
on pd.VehiID equals od.VehiID
into t
from rt in t.DefaultIfEmpty()
orderby pd.VehiID
select new
{
Id=(int?)rt.Id,
ThanaId=(int?)rt.ThanaID,
RoadID = (int?)rt.RoadID,
pd.VehiID,
pd.VehicleName,
pd.VehiDescription,
rt.CountHatDay,
rt.CountNonHatDay
}).ToList();
I have attached the table Design.How can i solve this ?
Update: I have tried Tim's approach using the conditional operator to avoid accesssing a property on a null reference. But i still get this error:
Upvotes: 1
Views: 801
Reputation: 460098
rt
will be null
if the VehiID
of RoadTrafficCount
doesn't exist in VehicleListRepository
. Then you get the exception on (int?)rt.Id
, (int?)rt.RoadID
and so on.
You can use the conditional operator to check if it's null
:
...
select new
{
Id = rt == null ? (int?)null : rt.Id,
ThanaId = rt == null ? (int?)null : rt.ThanaID,
RoadID = rt == null ? (int?)null : rt.RoadID,
pd.VehiID,
pd.VehicleName,
pd.VehiDescription,
rt.CountHatDay = rt == null ? (int?)null : rt.CountHatDay,
rt.CountNonHatDay = rt == null ? (int?)null : rt.CountNonHatDay
})
....
Upvotes: 1