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.
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
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 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.
public Item()
{
this.Sizes = new List<Size>();
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With