Item
可以包含多个Sizes
。当我尝试向项目添加新大小时,会抛出NullReference
错误。当我尝试将图像添加到我的项目时,会发生同样的事情。
对象引用未设置为对象的实例。
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; }
}
答案 0 :(得分:8)
您需要向Item初始化Sizes集合添加构造函数。自动属性简化了后备变量,但不对其进行初始化。
public Item()
{
this.Sizes = new List<Size>();
}
答案 1 :(得分:1)
我假设Item.Sizes
为空。您尚未初始化集合,因此item.Sizes.Add
会抛出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>();
}
}