简体   繁体   English

访问列表时实体框架 NullReferenceException

[英]Entity Framework NullReferenceException when accessing lists

I am using Windows Forms and I'm just learning Entity Framework and I have a question: I created a Customer class with a list type of Item and with Entity Framework I created a table for it.我正在使用 Windows 窗体,我只是在学习实体框架,我有一个问题:我创建了一个Customer类,其列表类型为Item并使用实体框架为它创建了一个表。 But when I try to get the list from it, I get a NullReference exception.但是当我尝试从中获取列表时,我收到了 NullReference 异常。

This are my classes:这是我的课程:

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; }
}

And this is the method I created to get the customer list based on the ID of the customer.这就是我创建的根据客户ID获取客户列表的方法。 I get the Id from the login and it works just fine:我从登录中获得了 Id,它工作得很好:

public List<Item> CustomerItems()
{
    using var context = new CustomerContext();

    var customer= context.Customers.Find(Id);
    var items = customer.Items;
    return items;
}

I wanted to use this method to update the datagrid and add new items to the list.我想使用这种方法来更新数据网格并将新项目添加到列表中。

I added some entries to the Item table but they don't show up in the datagrid.我在Item表中添加了一些条目,但它们没有显示在数据网格中。

Very likely the issue is related to:问题很可能与以下有关:

{
 var customer= context.Customers.Find(Id);
 var items = customer.Items;
 return items;
}

You should replace it with:您应该将其替换为:

{
 var customer= context.Customers.Include(x => x.Items).Find(Id);
 var items = customer.Items;
 return items;
}

You should also upvote @Den for his comment, just noticed it now.您还应该为@Den 的评论点赞,现在才注意到。

Please check theloading related data section of the docs for options how to load linked data.请检查文档的加载相关数据部分以获取如何加载链接数据的选项。

Also in this case you can just use proper query returning only needed data.同样在这种情况下,您可以只使用正确的查询返回仅需要的数据。 For example:例如:

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

In the code snippet presented above a NullReferenceException may occur in the access to Items in the expression customer.Items when customer is null .在上面提供的代码片段中,当customernull时,在访问表达式customer.Items Items可能会发生NullReferenceException The code should be modified to handle the null value, eg应修改代码以处理null值,例如

var items = (customer == null) ? null : customer.Items;

Note that in case of null customer method CustomerItems() will return a null item list, which needs handling elsewhere in the program.请注意,如果customer方法为null CustomerItems()将返回一个null项目列表,该列表需要在程序的其他地方进行处理。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM