NullReferenceException when trying to add in one-t

2020-07-18 10:54发布

Item can contain multiple Sizes. When I try to add new size to my item it throws NullReference error. Same thing happens when I try to add images to my item.

Object reference not set to an instance of an object.

Code

var size = new Size(){
    BasePrice = currentBasePrice, // not null, checked in debugger
    DiscountPrice = currentDiscountPrice // not null, checked in debugger
};

// item is not null, checked in debugger
item.Sizes.Add(size); // nothing here is null, however it throws null reference error here

Item Model

public class Item
{
    public int ID { get; set; }
    public int CategoryID { get; set; }
    virtual public Category Category { get; set; }
    virtual public ICollection<Size> Sizes { get; set; }
    virtual public ICollection<Image> Images { get; set; }
}

Size Model

public class Size
{
    public int ID { get; set; }
    public int ItemID { get; set; }
    virtual public Item Item { get; set; } // tried to delete this, did not help
    public decimal BasePrice { get; set; }
    public decimal? DiscountPrice { get; set; }
}

2条回答
一夜七次
2楼-- · 2020-07-18 11:14

You need to add a constructor to Item that initializes the Sizes collection. Auto properties simplifies a backing variable but does not initialize it.

public Item() 
{
    this.Sizes = new List<Size>();
}
查看更多
手持菜刀,她持情操
3楼-- · 2020-07-18 11:22

I assume that Item.Sizes is null. You haven't initialized the collection, hence item.Sizes.Add throws the NullReferenceException.

public class Item
{
    public int ID { get; set; }
    public int CategoryID { get; set; }
    virtual public Category Category { get; set; }
    virtual public ICollection<Size> Sizes { get; set; }
    virtual public ICollection<Image> Images { get; set; }

    public Item()
    {
        Sizes = new List<Size>();
    }
}
查看更多
登录 后发表回答