Home > Back-end >  Entity Framework NullReferenceException when accessing lists
Entity Framework NullReferenceException when accessing lists

Time:11-09

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.

CodePudding user response:

Please check the loading 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();

CodePudding user response:

In the code snippet presented above a NullReferenceExceptionmay 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, e.g.

var items = (customer == null) ? new List<Item>() : customer.Items;

CodePudding user response:

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.

  • Related