【问题标题】:Entity Framework NullReferenceException when accessing lists访问列表时的实体框架 NullReferenceException
【发布时间】:2021-11-07 18:17:54
【问题描述】:

我正在使用 Windows 窗体,我正在学习实体框架,我有一个问题:我创建了一个列表类型为 ItemCustomer 类,并使用实体框架为它创建了一个表。但是当我尝试从中获取列表时,我得到了一个 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 =&gt; x.Items).find(Id)

标签: c# entity-framework


【解决方案1】:

请查看文档的loading related data 部分,了解如何加载链接数据的选项。

同样在这种情况下,您可以使用正确的查询,只返回所需的数据。例如:

var items = context.Customers
    .Where(c => c.Id == Id)
    .SelectMany(c => c.Items)
    .ToList();

【讨论】:

    【解决方案2】:

    在上面给出的代码 sn-p 中,当 customernull 时,Items 的表达式 customer.Items 的访问中可能会出现 NullReferenceException。应修改代码以处理null 值,例如

    var items = (customer == null) ? new List&lt;Item&gt;() : customer.Items;

    【讨论】:

    • OP 特别提到客户 ID 是正确的。您应该反思您的答案,即不是客户为空而是项目属性的情况。
    • 答案基于上面的代码,并假设异常发生在这段代码中。空 Items 属性不会导致 NullReference 异常,因为此代码中未使用 Items,仅返回。
    • 我正在使用 CustomerItems 方法来获取客户拥有的项目,并且我正在尝试将新项目添加到返回的列表中。这就是它给我空异常的地方。
    • 好吧,那么异常发生在上面显示的代码之外?那么我的回答无效。从堆栈跟踪中,您可以看到问题所在。也许您应该将此代码添加到问题中。 CustomerItems() 可能没有任何问题。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-05-20
    • 1970-01-01
    相关资源
    最近更新 更多