Добавил:
Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:
lawrence_shaun_introducing_net_maui_build_and_deploy_crosspl.pdf
Скачиваний:
46
Добавлен:
26.06.2023
Размер:
5.15 Mб
Скачать

Chapter 9 Local Data

Mapping Your Models

Sqlite-net provides the ability to define mapping information in your model classes that will ultimately be used to create your table definition automatically for you. There is a rich set of options ranging from setting a PrimaryKey through to defining if a column has a MaxLength or even if it needs to be Unique. Open your Board.cs file and make the following modifications in bold:

using SQLite;

namespace WidgetBoard.Models;

public class Board

{

[PrimaryKey, AutoIncrement] public int Id { get; set; }

public string Name { get; init; }

public int NumberOfColumns { get; init; }

public int NumberOfRows { get; init; }

}

You add a new Id column, marking it as the PrimaryKey, and state that it will AutoIncrement, meaning that Sqlite will manage the id generation for you.

Your second model class is in the BoardWidget.cs file. This represents each widget that is placed on the board and where it is positioned.

using SQLite;

namespace WidgetBoard.Models;

274

Chapter 9 Local Data

public class BoardWidget

{

[PrimaryKey, AutoIncrement] public int Id { get; set; }

public int BoardId { get; set; }

public int Position { get; set; }

public string WidgetType { get; set; }

}

Creating Your Tables

You can inform the Sqlite-net connection to create a table for you. This can be done by calling the CreateTable<T> method and passing the appropriate model type. Note that CreateTable is idempotent, so unless you change your model, calling CreateTable a second time will have no impact. You can modify your SqliteBoardRepository to call the CreateTable method in its constructor as follows; changes in bold.

public SqliteBoardRepository(IFileSystem fileSystem)

{

var dbPath = Path.Combine(fileSystem.AppDataDirectory, "widgetboard_sqlite.db");

connection = new SQLiteConnection(dbPath); connection.CreateTable<Board>(); connection.CreateTable<BoardWidget>();

}

275

Chapter 9 Local Data

Inserting into an SQLite Database

You can now add in the ability to insert a board into your database by supplying the following implementation into the CreateBoard method:

public void CreateBoard(Board board)

{

connection.Insert(board);

}

Reading a Collection from an SQLite Database

You only need to return a list of the boards your user has created in the application.

public IReadOnlyList<Board> ListBoards()

{

return connection.Table<Board>()

.ToList();

}

Perhaps you should consider sorting these boards alphabetically. Sqlite-net offers a rich set of functionality when querying data in the database. You can make use of LINQ-based expressions, which gives you the following (the addition in bold):

public IReadOnlyList<Board> ListBoards()

{

return connection.Table<Board>()

.OrderBy(b => b.Name)

.ToList();

}

276

Chapter 9 Local Data

Reading a Single Entity from an SQLite Database

When reading a Board from the database, you also need to load any BoardWidgets that relate to it. For this you can write the following:

public Board LoadBoard(int boardId)

{

var board = connection.Find<Board>(boardId);

if (board is null)

{

return null;

}

var widgets = connection.Table<BoardWidget>().Where(w => w.BoardId == boardId).ToList();

board.BoardWidgets = widgets;

return board;

}

The first line calling Find allows you to find an entity with the supplied primary key value. This retrieves the Board. Next, you need to retrieve the collection of BoardWidgets. This is performed in a very similar manner

to loading your collection of Boards. Finally, you assign the widgets you loaded into the board before returning it to the caller.

It is worth noting that the sqlite-net-pcl package does not provide more complex querying operations such as joins. If this is something that you still require, it is possible to write the SQL directly and execute against

the connection. If you wish to join your Board and BoardWidget tables together, you can achieve this as follows:

277