| 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.
🔑 SQLite Basics in .NET MAUI
1. Why SQLite?
- Lightweight, serverless database.
- Perfect for mobile apps (Android/iOS) and desktop apps.
- Stores data locally in a single .db file.
2. Setting Up SQLite in MAUI
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
3. Creating a Model
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; }
}
4. Initializing the Database
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);
}
5. Getting the Database Path
Use FileSystem.AppDataDirectory in MAUI to store your .db file:
string dbPath = Path.Combine(FileSystem.AppDataDirectory, "mydb.db3");
var db = new DatabaseService(dbPath);
🚀 Next Steps
- Hook this up to your UI (e.g., a CollectionView bound to GetItemsAsync()).
- Add CRUD operations via buttons or swipe gestures.
- Consider using Dependency Injection to register DatabaseService for easy access across your app.
💡 Best Practices
- Always use asynchronous database methods to avoid blocking the UI thread.
- Keep database logic separate from UI logic using services and view models.
- Use proper error handling when performing database operations.
- Keep database connections centralized for better performance. ll
💻 Common Use Cases
- Offline-first mobile applications.
- To-do lists, notes, and productivity apps.
- Inventory and stock management systems.
- Form-based data collection apps.
⚠ Common Pitfalls
- Blocking UI thread by using synchronous database calls.
- Creating multiple database connections unnecessarily.
- Not handling exceptions and database migration properly.
- Not closing or managing connections efficiently.
🚀 Advanced Enhancements
- Implement MVVM architecture for clean separation of concerns.
- Add data encryption for sensitive user information.
- Use indexing to improve query performance.
- Enable cloud sync for cross-device data access.
| MAUI-Preferences-and-SecureStorage :👈 | 👉:MAUI-SQLite-Connection |