LINQ语句中的空异常,但返回LINQPAD中的结果

时间:2017-05-20 15:36:48

标签: c# linq

我下面有一条LINQ语句,应该将110条记录返回到我的视图中。当我检查SQL Server时,我的表中有记录,但是当我尝试根据Id检索这些记录并执行@foreach(var item in Model)时会导致空引用错误。任何帮助将不胜感激。

LINQPAD - 返回110条记录(RPT是架构)

RPT.Team_History.OrderByDescending (r => r.DateOfAction).Where(r => r.MgrID ==212) 

控制器代码(使用DB First方法。当VS生成模型时,RPT模式被丢弃)

 public PartialViewResult _TeamTransitionDisplay()
    {
        var mgrID = 212;
        IEnumerable<TeamHistoryViewModel> teamHistory;
        teamHistory = db.Team_History
                     .Where(x => x.MgrID == @mgrID)
                     .Select(x => new TeamHistoryViewModel
                     {
                         DateOfAction = x.ActionDate,
                         DeptID = x.DeptID,
                         Operation = x.Operation,
                         StartDate = x.StartDate,
                         AStartDate = x.AStartDate,
                         FStartDate = x.FStartDate
                     }).ToList();

        return PartialView("_TeamDisplay", teamHistory);
    }
  

[NullReferenceException:对象引用未设置为对象的实例。]

建议将不胜感激。

1 个答案:

答案 0 :(得分:0)

我认为,当它试图获取您的某个模型值时,它可能为null,因此它会抛出错误 你可以试试这个 对于可空属性添加检查,如果这是null,只为可空属性,我为所有添加因为我不知道哪些是可空的

teamHistory = db.Team_History
                 .Where(x => x.MgrID == @mgrID)
                 .Select(x => new TeamHistoryViewModel
                 {
                     DateOfAction = (x.ActionDate != null ? x.ActionDate : something here when null),
                     DeptID = (x.DeptID!= null ? x.DeptID: 0),
                     Operation = (x.Operation!= null ? x.Operation: "operation"),
                     StartDate = (x.StartDate!= null ? x.StartDate: DateTime.MinValue),
                     AStartDate = (x.AStartDate != null ? x.AStartDate : DateTime.MinValue),
                     FStartDate = (x.FStartDate != null ? x.FStartDate : DateTime.MinValue)
                 }).ToList();