0

I am trying to fetch data from SQL database and I am getting 5 records. But from that 5 list of records I want to create two lists separately. I am trying to do it a below:

public class ParentModel
{       
     public List<Model1> Child1 { get; set; }
     public List<Model2> Chil2{ get; set; }
}

My other two models are :

public class Model1
{
    public int Id { get; set; }
    public string Name { get; set; }
    public int? GroupNumber { get; set; }
    public string Description { get; set; }
}

public class Model2
{
     public string Name { get; set; }
     public int? Number { get; set; }
}

I would like to populate both the lists defined in ParentModel from my service but it is throwing null exception. How can I add data into my lists?

 public  ParentModel GetALL(int ID)
 {
    ParentModel objModel = new ParentModel();

    // here I fetch data from database using Iqueryable:
    IQueryable<Products> List = this._products.GetAll();
    var NamesList = List .Where(m => m.Id == ID).ToList();

    // Here I need to add data to my list. Also if it can be
    // followed in a best possible way, Please do share it with me.

    foreach (var obj in NamesList)
    {
        objModel.Child1.Add( new   Model1
        {
            Id=obj.Id, // Here it throws error of null exception
            Name = obj.Name,
            GroupNumber = obj.GroupNumber,
            Description =obj.Description
        }); 

        // the other list I would like to populate at the same time is
         objModel.Chil2.Add(new Model2
        {
            Name = obj.Name,
            Number = obj.Number
        });
    }
}
Sweetie
  • 1,298
  • 6
  • 24
  • 48

1 Answers1

1

There are a few methods. Easiest way is to add a constructor

public class ParentModel
    {

        public List<Model1> Child1 { get; set; }

        public List<Model2> Chil2 { get; set; }

        public ParentModel()
        {
            Child1 = new List<Model1>();
            Chil2 = new List<Model2>();
        }

    }
jdweng
  • 33,250
  • 2
  • 15
  • 20
  • That's Awesome. It is working fine. could you please explain it that why these properties need to be created with new or why it is necessary to allocate memory to properties first. As far as i know ,we can use any property of class without using new with constructor. – Sweetie Jun 11 '16 at 09:57
  • 1
    that is correct, and the correct property is returned. However, child1 and chil2 are both NULL when first initialized, and you can't call .Add on an null object. – DevilSuichiro Jun 11 '16 at 10:06
  • 1
    They are list objects and the {get;set} does not initialize lists. – jdweng Jun 11 '16 at 10:41