Overview
Data management is a cornerstone of mobile application development with .NET. It encompasses local storage, synchronization with cloud services, conflict resolution, and performance optimization.
Local Database (SQLite)
.NET provides robust support for SQLite through Microsoft.Data.Sqlite
. The API offers async methods optimized for mobile.
// Initialize a SQLite connection
using var connection = new Microsoft.Data.Sqlite.SqliteConnection("Data Source=app.db");
await connection.OpenAsync();
// Create a table
var createCmd = connection.CreateCommand();
createCmd.CommandText = @"
CREATE TABLE IF NOT EXISTS TodoItem (
Id INTEGER PRIMARY KEY AUTOINCREMENT,
Title TEXT NOT NULL,
IsCompleted INTEGER NOT NULL)";
await createCmd.ExecuteNonQueryAsync();
Sync Framework
The .NET Sync Framework enables bidirectional sync between local stores and cloud back‑ends (Azure, AWS, or custom services). It supports incremental sync, conflict detection, and custom migration.
// Configure a sync orchestrator
var orchestrator = new Microsoft.Synchronization.Orchestrator.SyncOrchestrator
{
LocalProvider = new SqliteSyncProvider("app.db"),
RemoteProvider = new AzureSyncProvider("https://myapp.azurewebsites.net/api/sync")
};
await orchestrator.SynchronizeAsync();
Learn more in the Sync Framework guide.
Cloud Sync Strategies
Choose a strategy that fits your app’s connectivity patterns:
Strategy | Use‑case | Implementation |
---|---|---|
Push‑only | Real‑time updates when online | SignalR or Azure App Service |
Pull‑only | Periodic background sync | Background services & timers |
Hybrid | Both push and fallback pull | Combine SignalR with background sync |
Example using Azure Mobile Apps SDK:
var client = new Microsoft.WindowsAzure.MobileServices.MobileServiceClient(
"https://myapp.azurewebsites.net");
// Get the sync table
var todoTable = client.GetSyncTable<TodoItem>();
// Pull changes
await todoTable.PullAsync("allTodoItems", todoTable.CreateQuery());
// Push local changes
await client.SyncContext.PushAsync();
See the full Cloud Sync documentation for advanced scenarios.
Complete Sample: Offline‑First Todo App
This sample demonstrates an offline‑first Todo app using SQLite, Sync Framework, and Azure Sync.
// MainPage.xaml.cs (simplified)
public partial class MainPage : ContentPage
{
private readonly TodoRepository _repo = new TodoRepository();
public MainPage()
{
InitializeComponent();
LoadItems();
}
private async void LoadItems()
{
var items = await _repo.GetAllAsync();
TodoList.ItemsSource = items;
}
private async void AddItem_Clicked(object sender, EventArgs e)
{
await _repo.AddAsync(new TodoItem { Title = NewItemEntry.Text, IsCompleted = false });
NewItemEntry.Text = "";
LoadItems();
}
private async void Sync_Clicked(object sender, EventArgs e)
{
await _repo.SyncAsync();
LoadItems();
}
}
Download the full project from GitHub.