简体   繁体   English

C#-使用List.Add时Class.models.modelname.list.get返回null

[英]C# - Class.models.modelname.list.get returned null when using List.Add

I built a class: 我建立了一个类:

public partial class SvcCodes
{
    public List<SvcCodeReport> Report { get; set; }
    public List<SvcCodesCheck> TestList { get; set; }
}

It uses this class: 它使用此类:

public partial class SvcCodeReport
{
    public List<Dictionary<string, object>> ProgResults { get; set; }
    public IEnumerable<ExtraData> ExtraData { get; set; }
}

In the controller, data is pulled from two sources and assigned to the SvcCodeReport class: 在控制器中,数据从两个来源中提取并分配给SvcCodeReport类:

var model = new SvcCodeReport()
{
  ProgResults = tasks,
  ExtraData = _context.ExtraData.Where(h => h.ServiceCode == Int32.Parse(id)
};

Then the model variable is added to the Report class: 然后将模型变量添加到Report类:

check.Report.Add(model);

But when I run the program, I get a null object error and a line that says: 但是,当我运行程序时,出现空对象错误,并显示一行:

LRProgReport.Models.SvcCodes.Report.get returned null

Is this error saying that Report is null BEFORE the add or after? 此错误是否表示在添加之前或之后Report为null?

If before, why is that an issue? 如果以前有,那是为什么呢? If after, why is the model variable not being added to the list? 如果之后,为什么不将模型变量添加到列表中?

You should initialize the Report list first and you can do it in the SvcCodes constructor; 您应该首先初始化Report列表,并且可以在SvcCodes构造函数中完成;

public partial class SvcCodes
{
    public List<SvcCodeReport> Report { get; set; }
    public List<SvcCodesCheck> TestList { get; set; }

    public SvcCodes()
    {
        Report = new List<SvcCodeReport>();
    }
}

I suspect you are falling fowl of Linq's deferred execution model. 我怀疑您不了解Linq的延迟执行模型。 When you do x.Where() etc the code is not run then. 当您执行x.Where()等时,代码不会运行。 It is only run when you finally force the data to be used. 仅当您最终强制使用数据时,它才会运行。 Try this instead 试试这个

var model = new SvcCodeReport()
{
  ProgResults = tasks,
  ExtraData = _context.ExtraData.Where(h => h.ServiceCode == Int32.Parse(id).ToList();
};

This will force _context.ExtraData to be evaluated right there 这将强制_context.ExtraData在此处进行评估

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

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