我有一堂课,用来查看Oreders列表
public class OrderVM
{
public OrderVM() { }
public OrderVM(OrderDTO row)
{
Id = row.Id;
ClientId = row.ClientId;
OrderDate = row.OrderDate;
}
public int Id { get; set; }
public string ClientId { get; set; }
public string OrderDate { get; set; }
public string ClientName { get; set; }
public string ClientSurname { get; set; }
}
我想在我的视图中看到的结果:
Name Surname Brand Mark
------- -------- ------------ --------
Alexey Petrov Jamis Trail
Scott SPark
Mongoose Expert
我决定将列表添加到 OrderVM 类中,以便每个客户都有购买的产品列表:
public class OrderVM
{
public OrderVM() { }
public OrderVM(OrderDTO row)
{
Id = row.Id;
ClientId = row.ClientId;
OrderDate = row.OrderDate;
Bicycles = new List<BicycleVM>();
}
public int Id { get; set; }
public string ClientId { get; set; }
public string OrderDate { get; set; }
public string ClientName { get; set; }
public string ClientSurname { get; set; }
public List<BicycleVM> Bicycles { get; set; }
}
public class BicycleVM
{
public int Id { get; set; }
public string Category { get; set; }
public int CategoryId { get; set; }
public string BrandName { get; set; }
public string Mark { get; set; }
public int Year { get; set; }
public string Color { get; set; }
public decimal WheelSize { get; set; }
public string Frame { get; set; }
public int Speeds { get; set; }
public string Brake { get; set; }
public string BicycleType { get; set; }
public decimal Weight { get; set; }
public decimal Price { get; set; }
public string PriceFormatted { get; set; }
[DisplayName("Image")]
public string ImageName { get; set; }
public IEnumerable<SelectListItem> Categories { get; set; }
public IEnumerable<string> GalleryImages { get; set; }
}
现在一切似乎都很好。现在,我需要填充此列表。 为此,我做了一个数据列表:
var orderedItems = db.Bicycles.ToArray().Where(x => listOfProductsIds.Contains(x.Id)).Select(x => new BicycleVM(x)).ToList();
如果我执行以下操作:
OrderVM order = new OrderVM();
order.Bicycles.AddRange( new List<BicycleVM>(orderedItems));
我正在获取对象引用未设置为对象的实例
我看到一些值,例如“类别”,“类别”,“图库图像”为空 对我来说没关系,因为我只需要BrandName,Mark和Price。
要避免这种情况,我有什么选择?
我正在考虑的是:
orderedItems.ForEach(x => x.Categories = " ");
orderedItems.ForEach(x => x.Category = " ");
orderedItems.ForEach(x => x.GalleryImages = " ");
orderedItems.ForEach(x => x.PriceFormatted = " ");
P.s。我已经读过这篇文章What is a NullReferenceException, and how do I fix it? 并且不确定如何正确使用此信息
答案 0 :(得分:1)
我认为,如果您在运行错误行之前检查order.Bicycles
,您会发现该错误将为null,因为您是使用空的构造函数创建了OrderVM
对象的({{1 }})。
只有接受new OrderVM());
作为输入的构造函数才会创建新的自行车清单。因此,当您使用其他(空)构造函数创建对象时,OrderDTO
永远不会执行,自行车清单仍为Bicycles = new List<BicycleVM>();
。
并且您无法在空对象上执行诸如null
之类的方法,这就是为什么您会得到异常的原因。
为了确保安全,您需要在两个构造函数中都运行AddRange()
。
示例:
Bicycles = new List<BicycleVM>();