0

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


}

1 Answers1

1

You haven't initialized your Orders property, so you can't add to it.

customer.Orders = new List<Order>();

You can also initialize it on the property itself (which I prefer so you can't forget it)

public List<Order> Orders { get; set; } = new List<Order>();
Aage
  • 5,932
  • 2
  • 32
  • 57