在maui项目中使用sqlite数据库,先在Nuget中搜索sqlite-net-pcl安装 ,再在搜索中输入sqlite空格green,搜索安装sqlitepclraw.bundle_green,如果不安装后者,将会报错。
在maui中体验一下sqlite,设计一个简单的笔记本simpleNotes,先建模型,在文件夹models中创建Note.cs。
using SQLite;
namespace SimpleNotes.Models
{
public class Note
{
[PrimaryKey,AutoIncrement]
public int NoteId { get; set; }
public string Title { get; set; }
public string Content { get; set; }
public DateTime CreationTime { get; set; }
public DateTime LastModifiedTime { get; set; }
}
}
在models文件夹中再建一个常量类,方便使用,文件名constants.cs。
namespace SimpleNotes.Models
{
public class Constants
{
private const string DBName = "notes.db3";
public const SQLite.SQLiteOpenFlags Flags = SQLite.SQLiteOpenFlags.Create |
SQLite.SQLiteOpenFlags.ReadWrite | SQLite.SQLiteOpenFlags.SharedCache;
public static string DatabasePath => Path.Combine(FileSystem.AppDataDirectory, DBName);
}
}
再在services文件夹建一个DatabaseService.cs,使用sqlite数据库的类。
using SimpleNotes.Models;
using SQLite;
namespace SimpleNotes.Services
{
public class DatabaseService
{
SQLiteAsyncConnection conn;
async Task Init()
{
if (conn is null)
{
conn = new SQLiteAsyncConnection(Constants.DatabasePath, Models.Constants.Flags);
await conn.CreateTableAsync<Note>();
}
}
public async Task<List<Models.Note>> GetAll()
{
await Init();
return await conn.Table<Models.Note>().ToListAsync();
}
public async Task<Models.Note> GetNote(Note note)
{
await Init();
var local = note;
if (local is not null)
{
return await conn.Table<Models.Note>().Where(n => n.NoteId == local.NoteId).FirstOrDefaultAsync();
}
return null;
}
public async Task<int> AddNoteAsync(Note note)
{
await Init();
var local = note;
if (local is not null)
{
if (local.NoteId == 0)
{
local.CreationTime = DateTime.Now;
local.LastModifiedTime = DateTime.Now;
return await conn.InsertAsync(local);
}
else
{
local.LastModifiedTime = DateTime.Now;
return await conn.UpdateAsync(local);
}
}
return -1;
}
public async Task<int> DeleteNoteAsync(Note note)
{
await Init();
var local = note;
if(local is not null)
{
var matchedNote = conn.Table<Note>().Where(n => n.NoteId == local.NoteId).FirstOrDefaultAsync();
if(matchedNote is not null)
{
return await conn.DeleteAsync(local);
}
}
return 0;
}
}
}
使用maui,不安装社区工具是不行的,真的是太方便了,提高效率,用nuget搜索安装communitytoolkit.maui和communitytoolkit.mvvm。
在viewmodels文件夹中创建AboutPageViewModel.cs。
namespace SimpleNotes.ViewModels
{
public class AboutPageViewM