Stan
Stan

Reputation: 26511

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

Upvotes: 4

Views: 2842

Answers (2)

Tim Schmelter
Tim Schmelter

Reputation: 460228

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

Upvotes: 1

Dharun
Dharun

Reputation: 613

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

Upvotes: 10

Related Questions