The only thing left to do in the repository is to implement the methods for getting, adding, and updating items:
- Locate the GetItems() method in the TodoItemRepository class.
- Update the GetItems() method with the following code:
public async Task<List<TodoItem>> GetItems()
{
await CreateConnection();
return await connection.Table<TodoItem>().ToListAsync();
}
To ensure that the connection to the database is valid, we call the CreateConnection() method we created in the previous section. When this method returns, we can make sure that it is initialized and that the TodoItem table has been created.
We then use the connection to access the TodoItem table and return a List<TodoItem> item that contains all the to-do list items in the database.
The code for adding items is even simpler:
- Locate the AddItem() method in the TodoItemRepository class.
- Update the AddItem() method with the following code:
public async Task AddItem(TodoItem item)
{
await CreateConnection();
await connection.InsertAsync(item);
OnItemAdded?.Invoke(this, item);
}
The call to CreateConnection() makes sure that we have a connection in the same way as we did for the GetItems() method. After this, we insert it into the database using the InsertAsync(...) method on the connection object. After an item has been inserted into the table, we invoke the OnItemAdded event to notify any subscribers.
The code to update an item is basically the same as the AddItem() method, but also includes calls to UpdateAsync and OnItemUpdated. Let's finish up by updating the UpdateItem() method with the following code:
- Locate the UpdateItem() method in the TodoItemRepository class.
- Update the UpdateItem() method with the following code:
public async Task UpdateItem(TodoItem item)
{
await CreateConnection();
await connection.UpdateAsync(item);
OnItemUpdated?.Invoke(this, item);
}
In the next section, we'll get started with MVVM. Grab a cup of coffee and let's get started!