Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c#

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:

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:

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?

If before, why is that an issue? If after, why is the model variable not being added to the list?

like image 656
Mighty Ferengi Avatar asked Sep 04 '26 07:09

Mighty Ferengi


2 Answers

You should initialize the Report list first and you can do it in the SvcCodes constructor;

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

    public SvcCodes()
    {
        Report = new List<SvcCodeReport>();
    }
}
like image 158
lucky Avatar answered Sep 06 '26 22:09

lucky


I suspect you are falling fowl of Linq's deferred execution model. When you do x.Where() etc the code is not run then. 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

like image 30
pm100 Avatar answered Sep 06 '26 22:09

pm100



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!