# Inventory System: Managing data using a database

:::{commons-figure} https://commons.wikimedia.org/wiki/File:Hand_in_filing_cabinet.jpg
:figwidth: 35%
:align: right
Hand in a filing cabinet.
:::


We will introduce databases for data input and output.

:::{card} 🤔 Question to ponder
1. What are the business data that we input in/ output from our inventory system?
1. How is data currently input and output?
1. What are the advantages & disadvantages of this approach?
:::

## Demo

:::{video} ../img/ISv4Database.webm
:figwidth: 55%
:align: right
:caption: Order processing with a database in the background. On the top, the tab `Order` shows the order data in the database. These are two orders by customers `Ramanda` and `Totoro`.
:::

The video on the right shows three aspects of using a database:

1. When we process one order, this is reflected in the database after we refresh `Order`.
1. If we restart the program, then the state is preserved in the database
1. If we change the database data, we can change the data shown by the program

## Requirements

1. Similar to previous week, build on the previous problem.
1. Your program must use a database called `inventory.sqlite` for getting the data for queued orders instead of static data through C#.

   Create the database using the example inventory data from last weeks.
1. If you used a `Dict` for `Stock`, then change it to a `List` of `Item`s and introduce a `Quantity` in `Item` instead.

   The database framework we will use cannot *navigate through* dictionaries but lists.
1. Modify your class diagram if needed.
1. Record a demonstration of your project similar to the video on the right.

## Tips

1. Read the database as the first step in `MainWindow()`. Otherwise orders may end up not being initialized which leads to empty list on the GUI
1. When reading the database, use `.Include().ThenInclude` statements to load aggregated classes. For example `OrderBook` needs to include `QueuedOrders`, which in turn needs to include `OrderLines` and finally `OrderLines` needs to include `Item` like this:

  ```cs
  public void ReadDatabase()
  {
      OrderBook = Db.OrderBooks
          .Include(o => o.QueuedOrders)
          .ThenInclude(o => o.OrderLines)
          .ThenInclude(o => o.Item)
          .Include(o => o.ProcessedOrders)
          .ThenInclude(o => o.OrderLines)
          .ThenInclude(o => o.Item)
          .ToList()[0];
  }
  ```
1. Write to the database after processing each order.