【问题标题】:NullReferenceException when trying to add in one-to-many relation尝试添加一对多关系时出现 NullReferenceException
【发布时间】:2012-10-04 11:41:40
【问题描述】:

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

【问题讨论】:

    标签: c# asp.net-mvc linq entity-framework asp.net-mvc-4


    【解决方案1】:

    您需要向 Item 添加一个初始化 Sizes 集合的构造函数。自动属性简化了后备变量,但不会对其进行初始化。

    public Item() 
    {
        this.Sizes = new List<Size>();
    }
    

    【讨论】:

      【解决方案2】:

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

      【讨论】:

        猜你喜欢
        • 2013-01-21
        • 2021-08-28
        • 2021-08-25
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-01-01
        • 2016-12-18
        • 2018-03-25
        相关资源
        最近更新 更多