如何在c#中将数据添加到Collection列表中

时间:2016-06-11 09:44:22

标签: c# entity-framework c#-4.0 entity-framework-4

我正在尝试从SQL数据库中获取数据,而我正在获取5条记录。但是从那5个记录列表中我想分别创建两个列表。我想在下面这样做:

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

我的另外两个模型是:

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

我想填充ParentModel中定义的列表 我的服务,但它抛出null异常。如何将数据添加到我的列表中?

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

1 个答案:

答案 0 :(得分:1)

有几种方法。最简单的方法是添加构造函数

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

    }