左外连接现在工作linq对象引用未设置为对象的实例

时间:2016-04-27 07:30:31

标签: c# sql-server linq

我想通过left outer join链接两个表格。为什么以下查询会返回此错误?

  

“linq查询对象引用未设置为对象的实例”

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();

我已附上表格Design.How我可以解决这个问题吗?

Table design picture

更新:我已尝试使用条件运算符Tim's approach来避免访问空引用上的属性。但我仍然得到这个错误:

enter image description here

1 个答案:

答案 0 :(得分:0)

如果rt中不存在null的{​​{1}},

VehiID将为RoadTrafficCount。然后,您会在VehicleListRepository(int?)rt.Id上获得例外,依此类推。

您可以使用条件运算符来检查它是否为(int?)rt.RoadID

null