简体   繁体   中英

Null exception in LINQ statement, but returns results in LINQPAD

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM