I have a class that I use to see list of 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; }
}
the result I want to see this in my View:
Name Surname Brand Mark
------- -------- ------------ --------
Alexey Petrov Jamis Trail
Scott SPark
Mongoose Expert
I decided to add a List to the class OrderVM so every client will have a List of purchased products:
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; }
}
now all seems good. Now I need to populate this List. To do this I did a list with data:
var orderedItems = db.Bicycles.ToArray().Where(x => listOfProductsIds.Contains(x.Id)).Select(x => new BicycleVM(x)).ToList();
inside the list 4 items with values:
if I do the following:
OrderVM order = new OrderVM();
order.Bicycles.AddRange( new List<BicycleVM>(orderedItems));
I'm getting exeption Object reference not set to an instance of an object
I see that some Values like Categories, Category, GalleryImages are null For me it's Ok because I only need BrandName, Mark and Price.
What options do I have to avoid this exeption?
What I'm thinking about is:
orderedItems.ForEach(x => x.Categories = " ");
orderedItems.ForEach(x => x.Category = " ");
orderedItems.ForEach(x => x.GalleryImages = " ");
orderedItems.ForEach(x => x.PriceFormatted = " ");
P.s. I have read this article What is a NullReferenceException, and how do I fix it? and not sure how correct use this information for my case