gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 13:48:23 25 4
gpt4 key购买 nike

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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com