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

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

Item 可以包含多个 Sizes。当我尝试向我的项目添加新尺寸时,它会抛出 NullReference 错误。当我尝试将图像添加到我的项目时,也会发生同样的事情。

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

最佳答案

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

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

关于c# - 尝试添加一对多关系时出现 NullReferenceException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12726480/

相关文章:

javascript - 仅加载页面内的特定 DIV

c# - 如何在 Linq C# 中执行此操作

c# - LINQ 到 SQL : Alter Table or Add New Table to Existing Database

c# - LINQ to Entities 与文化冲突

c# - 无法翻译 LINQ 表达式

c# - 保存文档文件的问题

c# - windows服务的备份算法

c# - 然后 Linq 无限期地运行

c# - 连接表,获取对象引用未设置

c# - PhoneGap 开发 ASP.NET MVC 应用程序