Gestionnaire de configurations > plateforme > x86 (ou x64)
Puis dans le gestionnaire de paquets NuGet :
- chercher SQLite for Windows Runtime
- puis SQLite.net
On peut créer la base et les tables en mode « Code First » un peu de la même manière qu’avec Entity Framework
(SQLite ne prend pas en charge les clés étrangères)
using SQLite ;
La classe métier qui sert de « schéma » pour la table .J’implémente INotifyPropertyChanged pour le binding
Les attributs appartiennent à l’espace de noms SQLite .Les attributs disponibles sont :
- TableAttribute
- ColumnAttribute
- PrimaryKeyAttribute
- AutoIncrementAttribute : colonne de clé primaire auto incrémentée.
- IndexedAttribute : colonne avec un index
- IgnoreAttribute : colonne ignorée lors de la création de la table
- UniqueAttribute : colonne avec valeurs uniques
- MaxLengthAttribute : taille maximale de la donnée d’une colonne
- CollationAttribute
Model
[Table("Client")] public class Client : ObservedBase {
private int _clientID;
[PrimaryKey] [AutoIncrement] [Column("ClientID")] public int ClientID { get { return _clientID; } set { _clientID = value; RaisePropertyChanged<int>(() => ClientID); } }
private string _clientFullName;
[MaxLength(100)] [Column("ClientFullName")] public string ClientFullName { get { return _clientFullName; } set { _clientFullName = value; RaisePropertyChanged<string>(() => ClientFullName); } }
private string _email;
[Column("Email")] public string Email { get { return _email; } set { _email = value; RaisePropertyChanged<string>(() => Email); } } } |
ObservedBase
public class ObservedBase : INotifyPropertyChanged { public ObservedBase() { }
#region INotifyPropertyChanged Members
public event PropertyChangedEventHandler PropertyChanged;
protected void RaisePropertyChanged<T>(Expression<Func<T>> expression) {
var memberExpression = expression.Body as MemberExpression; if (memberExpression != null) { string propertyName = memberExpression.Member.Name; RaisePropertyChanged(propertyName); } }
private void RaisePropertyChanged(String propertyName) { PropertyChangedEventHandler handler = PropertyChanged; if (handler != null) handler(this, new PropertyChangedEventArgs(propertyName));
}
#endregion } |
Dans Une classe ClientService implémentant une interface IClientService pour structurer un minimum son code .
Créer une base :la base est automatiquement crée dans le répertoire cible si elle n’existe pas .Il est conseillé d’appeler cette méthode le plus tôt possible (dès OnLaunched dans App.xaml.cs)
private SQLiteAsyncConnection connection;
public void GetConnection() { string path = Path.Combine(ApplicationData.Current.LocalFolder.Path, "dbDemo.sqlite"); connection = new SQLiteAsyncConnection(path); } |
Créer une table : on utilise la méthode CreateTableAsync<T>() .Il existe également une méthode CreateTablesAsync() (pour supprimer une table on peut utiliser DropTableAsync<T>())
public async Task CreateTableAsync() { await connection.CreateTableAsync<Client>(); } |
Récupérer les lignes
public async Task<IList<Client>> GetAll() { return await connection.Table<Client>().ToListAsync(); } |
Récupérer un élément
public async Task<Client> GetOne() { GetConnection(); return await connection.Table<Client>().FirstOrDefaultAsync(); } |
Insérer un ou plusieurs éléments
public async Task AddClientsAsync() { List<Client> clients = new List<Client>(){ new Client(){ClientFullName="Bellin, Marie",Email="bellinmarie@live.com"}, new Client(){ClientFullName="Adams, Terry",Email="adams156@live.com"} };
// await connexion.InsertAsync(client); // pour insérer un élément await connection.InsertAllAsync(clients); // pour insérer une collection } |
Modifier un élément (il existe aussi UpdateAllAsync)
public async Task<int> Remove(Client client) { GetConnection(); return await connection.UpdateAsync(client); } |
Supprimer un élément
public async Task<int> Remove(Client client) { GetConnection(); return await connection.DeleteAsync(client); } |
Le code du ViewModel
public class ClientListViewModel :ObservedBase { private ObservableCollection<Client> _clients;
public ObservableCollection<Client> Clients { get { return _clients; } set { _clients = value; RaisePropertyChanged<ObservableCollection<Client>>(() => Clients); } }
private IClientService clientService;
public ClientListViewModel() { clientService = new ClientService(); GetItems(); }
public async void GetItems() { Clients = new ObservableCollection<Client>(await clientService.GetAll()); } } |
Et MainPage
<Grid Background="{ThemeResource ApplicationPageBackgroundThemeBrush}"> <GridView ItemsSource="{Binding Clients}" HorizontalAlignment="Stretch" VerticalAlignment="Stretch"> <GridView.ItemTemplate> <DataTemplate> <StackPanel Orientation="Horizontal"> <TextBlock Text="{Binding ClientID}" Width="100"/> <TextBox Text="{Binding ClientFullName}" Width="150"/> <TextBox Text="{Binding Email}" Width="200" /> </StackPanel> </DataTemplate> </GridView.ItemTemplate> </GridView> </Grid> |
Dans le code behind simplement
this.DataContext = new ClientListViewModel();