Edit: I am not asking about what System.NullReferenceException is. I'm trying to understand why the list property of the object is null and how to prevent it.
When i try to add a new item to my customer's orders list, i am getting System.NullReferenceException. I thought about making list property static but i am not sure that is the correct way. What is the proper way of defining classes in this case?
using(var northwindContext = new NorthwindContext())
{
Customer customer = northwindContext.Customers.Find("ENGIN");
customer.Orders.Add(
new Order {
OrderId = 1,
OrderDate = DateTime.Now,
ShipCity = "Ankara",
ShipCountry = "Türkiye"
});
northwindContext.SaveChanges();
}
public class Customer
{
public string CustomerID { get; set; }
public string ContactName { get; set; }
public string CompanyName { get; set; }
public string City { get; set; }
public string Country { get; set; }
public List<Order> Orders { get; set; }
}
public class Order
{
public int OrderId { get; set; }
public string CustomerID { get; set; }
public string ShipCity { get; set; }
public string ShipCountry { get; set; }
public DateTime OrderDate { get; set; }
public Customer Customer { get; set; }
}