Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NullReferenceException when trying to add in one-to-many relation

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; }
}
like image 864
Stan Avatar asked Dec 20 '22 15:12

Stan


1 Answers

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>();
}
like image 63
Dharun Avatar answered May 03 '23 06:05

Dharun