首页 > 解决方案 > 访问列表时的实体框架 NullReferenceException

问题描述

我正在使用 Windows 窗体,我正在学习实体框架,我有一个问题:我创建了Customer一个列表类型的类,Item并使用实体框架为它创建了一个表。但是当我尝试从中获取列表时,我得到一个 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但它们没有出现在数据网格中。

标签: c#entity-framework

解决方案


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

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

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

推荐阅读