c# - 访问列表时的实体框架 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
但它们没有出现在数据网格中。
解决方案
请查看文档的加载相关数据部分,了解如何加载链接数据的选项。
同样在这种情况下,您可以只使用正确的查询,只返回需要的数据。例如:
var items = context.Customers
.Where(c => c.Id == Id)
.SelectMany(c => c.Items)
.ToList();
推荐阅读
- javascript - 为什么响应式图像地图插件不起作用?
- unix - 在执行之前使用 iTerm2 情绪化和按摩命令
- python - UGPlus Gread() 函数不断返回 b'\n'
- css - viewport height (100vh) on mobile leads to unwanted scroll
- php - Laravel 8 上的 ArgumentCountError
- python - Python BeautifulSoup 附加没有最外层标签的内容
- .net - UWP 中 ListView 项目的 DoubleTapped 事件
- javascript - 解析openweathermap api响应数据node.js时JSON输入意外结束
- php - 将操作挂钩到 WP_User->add_cap() 和 WP_User->remove_cap()
- excel - 用最后一行的值填充 Column 中的所有行。VBA 错误。未设置对象变量或 With 块变量