尝试添加一对多关系时出现NullReferenceException

Sta*_*tan 3 c# linq asp.net-mvc entity-framework asp.net-mvc-4

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
Run Code Online (Sandbox Code Playgroud)

项目模型

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; }
}
Run Code Online (Sandbox Code Playgroud)

尺寸模型

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; }
}
Run Code Online (Sandbox Code Playgroud)

Dha*_*run 8

您需要向初始化Sizes集合的Item添加构造函数.自动属性简化了后备变量,但未初始化它.

public Item() 
{
    this.Sizes = new List<Size>();
}
Run Code Online (Sandbox Code Playgroud)