0

I have a LINQ statement below which should return 110 records back to my view. When I checked SQL Server, my table has records in it, but when I try to retrieve those records based on an Id and do @foreach(var item in Model) its causing a null reference error. Any help would be appreciated.

LINQPAD --Returns 110 records (RPT is the schema)

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

Controller Code (DB First approach used. RPT schema dropped when VS generated models)

 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: Object reference not set to an instance of an object.]

Advice would be appreciated.

Erik Philips
  • 53,428
  • 11
  • 128
  • 150
LifeOf0sAnd1s
  • 113
  • 1
  • 11
  • What's the full exception? Are you sure db isn't null at that point? – Pete M May 20 '17 at 15:41
  • Possible duplicate of [What is a NullReferenceException, and how do I fix it?](http://stackoverflow.com/questions/4660142/what-is-a-nullreferenceexception-and-how-do-i-fix-it) – Erik Philips May 20 '17 at 15:47

1 Answers1

0

I think, When it is trying to get one of your model values, it might be null, so it is throwing the error You can try this for nullable properties add checking if this is null, only for nullable properties, i added for all because i don't know which are nullable

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();
Munzer
  • 2,216
  • 2
  • 18
  • 25