| MAUI-Preferences-and-SecureStorage | MAUI-SQLite-Connection | |
MAUI Local Databases with SQLite |
MAUI local databases with SQLite. Since you already have a tab open for MAUI-index, let’s break down the basics so you can connect the dots between your project and SQLite integration.
Add the SQLite-net-pcl NuGet package to your project.
This gives you simple ORM-like functionality for SQLite.
dotnet add package sqlite-net-pcl
Define your data model with attributes:
using SQLite;
public class TodoItem
{
[PrimaryKey, AutoIncrement]
public int Id { get; set; }
[MaxLength(250)]
public string Name { get; set; }
public bool IsCompleted { get; set; }
}
You’ll typically create a helper class to manage the connection:
public class DatabaseService
{
readonly SQLiteAsyncConnection _database;
public DatabaseService(string dbPath)
{
_database = new SQLiteAsyncConnection(dbPath);
_database.CreateTableAsync<TodoItem>().Wait();
}
public Task<List<TodoItem>> GetItemsAsync() =>
_database.Table<TodoItem>().ToListAsync();
public Task<int> SaveItemAsync(TodoItem item) =>
_database.InsertOrReplaceAsync(item);
public Task<int> DeleteItemAsync(TodoItem item) =>
_database.DeleteAsync(item);
}
Use FileSystem.AppDataDirectory in MAUI to store your .db file:
string dbPath = Path.Combine(FileSystem.AppDataDirectory, "mydb.db3"); var db = new DatabaseService(dbPath);
| MAUI-Preferences-and-SecureStorage | MAUI-SQLite-Connection | |