###### tags: `MAUI + Blazor` # MAUI + 本機資料庫(SQLite) (.Net6.0) ## SQLite的建置 [.NET MAUI 本機資料庫](https://learn.microsoft.com/zh-tw/dotnet/maui/data-cloud/database-sqlite?view=net-maui-6.0)  首先要使用套件, 如上圖 安裝好之後要設定連接字串, 創建一個類別叫做Constants 貼上下面的原始碼 ```C# public static class Constants { public const string DatabaseFilename = "TodoSQLite.db3"; public const SQLite.SQLiteOpenFlags Flags = // open the database in read/write mode SQLite.SQLiteOpenFlags.ReadWrite | // create the database if it doesn't exist SQLite.SQLiteOpenFlags.Create | // enable multi-threaded database access SQLite.SQLiteOpenFlags.SharedCache; public static string DatabasePath => Path.Combine(FileSystem.AppDataDirectory, DatabaseFilename); } ``` 創建一個類別叫做TodoItemRepositroy 貼上下面的原始碼 ``` public class TodoItemRepositroy { SQLiteAsyncConnection Database; public TodoItemRepositroy() { } async Task Init() { if (Database is not null) return; Database = new SQLiteAsyncConnection(Constants.DatabasePath, Constants.Flags); var result = await Database.CreateTableAsync<TodoItem>(); } public async Task<List<TodoItem>> GetItemsAsync() { await Init(); return await Database.Table<TodoItem>().ToListAsync(); } public async Task<TodoItem> GetItemAsync(int id) { await Init(); return await Database.Table<TodoItem>().Where(i => i.Id == id).FirstOrDefaultAsync(); } public async Task<int> SaveItemAsync(TodoItem item) { await Init(); if (item.Id != 0) return await Database.UpdateAsync(item); else return await Database.InsertAsync(item); } public async Task<int> DeleteItemAsync(TodoItem item) { await Init(); return await Database.DeleteAsync(item); } } ``` 創建一個類別叫做TodoItem, 用來創建資料庫的欄位 貼上下面的原始碼 ``` [Table("TodoItem")] public class TodoItem { [PrimaryKey, AutoIncrement] public int Id { get; set; } [MaxLength(100)] public string Todo { get; set; } public DateTime? DueDate { get; set; } } ``` 這樣對資料庫的 TodoItem CRUD就有了 再來去MauiProgram.cs裡面把TodoItemRepositroy給注入 貼上下面的原始碼 ``` builder.Services.AddSingleton<TodoItemRepositroy>(); ``` 注入好之後, 就去App.xaml把這個服務做成全域的, 如下圖  添加一個靜態的TodoItemRepositroy 然後在APP裡面接收TodoItemRepositroy並賦予靜態的Repo 這樣就可以在任何地方使用這個資料庫 ## 使用SQLite 接下來我將使用 "待辦事項" 這個功能做SQLite的演示 原始碼如下 ``` <h3>TodoList</h3> <ul> <li> 待辦事項 ( 截止時間 )</li> @foreach (var item in Todos) { <li> @item.Todo ( @item.DueDate )</li> } </ul> <input @bind="NewTodo" @bind:event="oninput" placeholder="待辦事項?"/> <input @bind="DueDate" @bind:format="yyyy-MM-dd" placeholder="截止時間" /> <button @onclick="Save">Save</button> @if (!string.IsNullOrEmpty(NewTodo)) { <p>@NewTodo Due: @DueDate?.ToShortDateString()</p> } @code { private List<TodoItem> Todos = new(); private string NewTodo = string.Empty; private DateTime? DueDate = null; protected override async Task OnParametersSetAsync() { Todos = await App.Repo.GetItemsAsync(); } private async void Save() { if (string.IsNullOrEmpty(NewTodo)) return; var todoItem = new TodoItem { Todo = NewTodo, DueDate = DueDate }; Todos.Add(todoItem); NewTodo = string.Empty; DueDate = null; await App.Repo.SaveItemAsync(todoItem); } } ``` 這樣使用SQLite的簡單的待辦功能就完成了
×
Sign in
Email
Password
Forgot password
or
By clicking below, you agree to our
terms of service
.
Sign in via Facebook
Sign in via Twitter
Sign in via GitHub
Sign in via Dropbox
Sign in with Wallet
Wallet (
)
Connect another wallet
New to HackMD?
Sign up