-2

I have these Models

public class Order
{
    public string Id { get; set; }
    public List<ItemsOrdered> Items { get; set; }
}

public class ItemsOrdered
{
    public string Id { get; set; }
    public Item Item { get; set; }
    public int Quantity { get; set; }
}
public class Item 
{
    // some props
}

I can set the data in the database using the database context and i can view the data in the mysql database, I can get the Order using

var order = context.Orders.First(c => c.Id == id)

and it returns the order, but if I want to get the Items list of the Order by

order.Items

it returns null and i get the exception:

Object referece not set to an instance of an object.

  • Does this answer your question? [What does "Object reference not set to an instance of an object" mean?](https://stackoverflow.com/questions/779091/what-does-object-reference-not-set-to-an-instance-of-an-object-mean) – Tân Jul 29 '20 at 09:41
  • 1
    Have you enabled lazy loading or used include? – Mafii Jul 29 '20 at 09:45
  • you should add the db-technology that you use (eg. Entity-Framework) as tag – Mong Zhu Jul 29 '20 at 11:29

2 Answers2

0

There's a number of reasons as to why the exception is throwing, but catching the exception will give you more details as to what is happening. For instance, you may be pulling an order, but the order may not have any items associated with it:

Order order = new Order();
List<ItemsOrdered> orderItems = new List<ItemsOrdered>();
try {
    order = context.orders.First(c => c.Id = id);
    orderItems = order.Items;
} catch (Exception e){
    Debug.WriteLine(e.Message);
    //Do what you will here...
}

If there are no orders, then you'll have an empty list, and thus the error will throw when you try to reference it.

Clarke185
  • 1
  • 1
  • i get the order for sure but the problem is with the specific object properties. the comment with the lazy loading may help me – Mihai Anghelin Jul 29 '20 at 10:12
0

Use something like this :

 order = context.orders.Include(o=> o.Items).First(c => c.Id = id);
yanis 13
  • 16
  • 1