C# 为什么是列表<&燃气轮机;对象的属性为空
编辑:我不是问System.NullReferenceException是什么。我试图理解为什么对象的list属性为null,以及如何防止它 当我尝试将新项目添加到客户的订单列表时,我得到System.NullReferenceException。我曾考虑过将列表属性设置为静态,但我不确定这是正确的方法。 在这种情况下,定义类的正确方法是什么C# 为什么是列表<&燃气轮机;对象的属性为空,c#,entity-framework,C#,Entity Framework,编辑:我不是问System.NullReferenceException是什么。我试图理解为什么对象的list属性为null,以及如何防止它 当我尝试将新项目添加到客户的订单列表时,我得到System.NullReferenceException。我曾考虑过将列表属性设置为静态,但我不确定这是正确的方法。 在这种情况下,定义类的正确方法是什么 using(var northwindContext = new NorthwindContext()) {
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; }
}
使用(var northwindContext=new northwindContext())
{
Customer=northwindContext.Customers.Find(“引擎”);
customer.Orders.Add(
新秩序{
OrderId=1,
OrderDate=DateTime。现在,
ShipCity=“安卡拉”,
ShipCountry=“Türkiye”
});
northwindContext.SaveChanges();
}
公共类客户
{
公共字符串CustomerID{get;set;}
公共字符串ContactName{get;set;}
公共字符串CompanyName{get;set;}
公共字符串City{get;set;}
公共字符串国家{get;set;}
公共列表顺序{get;set;}
}
公共阶级秩序
{
公共int-OrderId{get;set;}
公共字符串CustomerID{get;set;}
公共字符串ShipCity{get;set;}
公共字符串ShipCountry{get;set;}
public DateTime OrderDate{get;set;}
公共客户客户{get;set;}
}
您尚未初始化您的订单
属性,因此无法添加到该属性中
customer.Orders = new List<Order>();
customer.Orders=新列表();
您还可以在属性本身上初始化它(我更喜欢这样,这样您就不会忘记它)
公共列表顺序{get;set;}=new List();
public List<Order> Orders { get; set; } = new List<Order>();