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; }
}
You need to add a constructor to Item that initializes the Sizes collection. Auto properties simplifies a backing variable but does not initialize it.
I assume that
Item.Sizes
is null. You haven't initialized the collection, henceitem.Sizes.Add
throws theNullReferenceException
.