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