简体   繁体   English

LINQ语句中为Null异常,但在LINQPAD中返回结果

[英]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. 我下面有一个LINQ语句,该语句应将110条记录返回到我的视图。 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. 当我检查SQL Server时,我的表中有记录,但是当我尝试基于一个ID检索这些记录并执行@foreach(var item in Model)导致空引用错误。 Any help would be appreciated. 任何帮助,将不胜感激。

LINQPAD --Returns 110 records (RPT is the schema) LINQPAD-返回110条记录(RPT是模式)

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) 控制器代码 (使用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: Object reference not set to an instance of an object.] [NullReferenceException:对象引用未设置为对象的实例。

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 我认为,当它尝试获取您的模型值之一时,它可能为null,因此引发错误。您可以尝试对可为空的属性添加此检查,如果只有nullable,则检查是否为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();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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