【发布时间】:2021-11-07 18:17:54
【问题描述】:
我正在使用 Windows 窗体,我正在学习实体框架,我有一个问题:我创建了一个列表类型为 Item 的 Customer 类,并使用实体框架为它创建了一个表。但是当我尝试从中获取列表时,我得到了一个 NullReference 异常。
这是我的课程:
public class Item
{
public int Id{ get; set; }
public string ItemName { get; set; }
public decimal Price { get; set; }
public int Quantity { get; set; }
}
public class Customer
{
public int Id { get; set; }
public string UserName { get; set; }
public string PassWord { get; set; }
public List<Item> Items { get; set; }
}
这是我创建的基于客户的ID 获取客户列表的方法。我从登录中获得了 ID,它工作得很好:
public List<Item> CustomerItems()
{
using var context = new CustomerContext();
var customer= context.Customers.Find(Id);
var items = customer.Items;
return items;
}
我想用这种方法更新数据网格并将新项目添加到列表中。
我在Item 表中添加了一些条目,但它们没有显示在数据网格中。
【问题讨论】:
-
您没有足够的代码来解释您的问题。首先, Find(Id) 通常只会返回 1 个项目,而不是列表。但如果确实如此,并且您的列表为空,则某些内容未正确映射。如果没有项目,它通常会返回一个空列表。不是空值。您必须通过调试(调试模式)跟踪它发生的确切位置,或者如果您需要帮助,至少还包括异常的堆栈跟踪。
-
我正在使用 find 来获取具有相应 ID 的客户,如果您需要另一个代码块,我可以为您提供它,我可以使用它访问其项目列表。
-
用 ICollection 替换 List 并使这个属性成为虚拟的。
-
您的商品如何与客户关联?在一对多关系中,Items 表需要一个客户 ID 列(CustomerId 或 Customer_Id),您需要为添加的每个项目填充该列。
-
在您的查询中添加包含。
context.Customers.Include(x => x.Items).find(Id)
标签: c# entity-framework