在C#中向对象添加列表

时间:2018-12-06 15:47:38

标签: c# asp.net-mvc entity-framework

由于找不到相似的问题或示例,我显然在错误地考虑这一点。我实例化了一个对象,并希望向该对象添加一个列表,但是却无法找到正确的语法。将列表添加到对象的正确方法是什么?

List<business> businesses = (from j in db.business.Include("rooms") where j.status == "active" select j).ToList();

List<listing> listings = new List<listing>();

foreach(business b in businesses)
{
    listing l = new listing();
    l.id = b.id;
    l.title = b.title;
    listings.Add(l);
    List<listingrooms> listingrooms = new List<listingrooms>();
    List<listingamenities> listingamenities = new List<listingamenities>();

    foreach (rooms r in b.rooms)
    {
        listingrooms lr = new listingrooms();
        lr.id = r.id;
        lr.createDate = r.createDate;
        lr.doubleBeds = r.doubleBeds;
        lr.kingBeds = r.kingBeds;
        lr.numberCabins = r.numberCabins;
        lr.numberRooms = r.numberRooms;
        lr.numberSites = r.numberSites;
        lr.numberSuites = r.numberSuites;

        l.listingrooms.Add(lr);
    }
}

我的课...

public class listing
{    
    public string title { get; set; }
    public int id { get; set; }

    public virtual ICollection<listingrooms> listingrooms { get; set; }
}

public partial class listingrooms
{
    public Nullable<int> numberRooms { get; set; }
    public Nullable<int> numberSuites { get; set; }
    public Nullable<int> kingBeds { get; set; }
    public Nullable<int> doubleBeds { get; set; }
    public Nullable<int> numberCabins { get; set; }
    public Nullable<int> numberSites { get; set; }
    public System.DateTime createDate { get; set; }
    public int id { get; set; }

    public virtual listing listing { get; set; }
}

1 个答案:

答案 0 :(得分:2)

您没有初始化列表:

public class listing
{    

    public listing() // Create a costructor
    {
        // Initialize your List
        listingrooms = new List<listingrooms>();
    }

    public string title { get; set; }
    public int id { get; set; }

    public virtual ICollection<listingrooms> listingrooms { get; set; }
}