简体   繁体   中英

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. But when I try to get the list from it, I get a NullReference exception.

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. I get the Id from the login and it works just fine:

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.

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.

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 . The code should be modified to handle the null value, eg

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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