Belajar Avalonia #8 Avalonia CURD Dengan SQLITE
Avalonia adalah framework UI berbasis .NET yang bersifat cross-platform, dan SQLite adalah database ringan yang sering digunakan untuk aplikasi desktop. Berikut adalah tutorial sederhana untuk membuat aplikasi CRUD (Create, Read, Update, Delete) menggunakan Avalonia dan SQLite.
1. Persiapan Proyek
Pastikan Anda telah menginstal .NET SDK. Jika belum, unduh dari situs resmi .NET.
Buat proyek Avalonia baru:
dotnet new avalonia.app -o AvaloniaCrudApp
cd AvaloniaCrudApp
Tambahkan paket NuGet yang dibutuhkan:
dotnet add package Microsoft.Data.Sqlite
dotnet add package Dapper
dotnet add package Avalonia.ReactiveUI
2. Membuat Model
Buat folder Models dan buat file Person.cs
:
using System.ComponentModel;
using System.Runtime.CompilerServices;
namespace AvaloniaCrudApp.Models
{
public class Person : INotifyPropertyChanged
{
private int _id;
private string _name;
private int _age;
public int Id
{
get => _id;
set { _id = value; OnPropertyChanged(); }
}
public string Name
{
get => _name;
set { _name = value; OnPropertyChanged(); }
}
public int Age
{
get => _age;
set { _age = value; OnPropertyChanged(); }
}
public event PropertyChangedEventHandler? PropertyChanged;
protected void OnPropertyChanged([CallerMemberName] string? name = null)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(name));
}
}
}
3. Mengatur Database
Buat folder Data dan buat file Database.cs
:
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Linq;
using Dapper;
using Microsoft.Data.Sqlite;
namespace AvaloniaCrudApp.Data
{
public static class Database
{
private static string DbPath = "database.db";
static Database()
{
using var connection = GetConnection();
connection.Execute(@"
CREATE TABLE IF NOT EXISTS People (
Id INTEGER PRIMARY KEY AUTOINCREMENT,
Name TEXT NOT NULL,
Age INTEGER NOT NULL
)");
}
public static IDbConnection GetConnection()
{
return new SqliteConnection($"Data Source={DbPath}");
}
public static List<Models.Person> GetAllPeople()
{
using var connection = GetConnection();
return connection.Query<Models.Person>("SELECT * FROM People").ToList();
}
public static void InsertPerson(Models.Person person)
{
using var connection = GetConnection();
connection.Execute("INSERT INTO People (Name, Age) VALUES (@Name, @Age)", person);
}
public static void UpdatePerson(Models.Person person)
{
using var connection = GetConnection();
connection.Execute("UPDATE People SET Name = @Name, Age = @Age WHERE Id = @Id", person);
}
public static void DeletePerson(int id)
{
using var connection = GetConnection();
connection.Execute("DELETE FROM People WHERE Id = @Id", new { Id = id });
}
}
}
4. Membuat ViewModel
Buat folder ViewModels dan buat file MainViewModel.cs
:
using System.Collections.ObjectModel;
using System.Windows.Input;
using AvaloniaCrudApp.Data;
using AvaloniaCrudApp.Models;
using ReactiveUI;
namespace AvaloniaCrudApp.ViewModels
{
public class MainViewModel : ReactiveObject
{
private Person _selectedPerson = new Person();
public ObservableCollection<Person> People { get; } = new(Database.GetAllPeople());
public Person SelectedPerson
{
get => _selectedPerson;
set => this.RaiseAndSetIfChanged(ref _selectedPerson, value);
}
public ICommand AddCommand => ReactiveCommand.Create(AddPerson);
public ICommand UpdateCommand => ReactiveCommand.Create(UpdatePerson);
public ICommand DeleteCommand => ReactiveCommand.Create(DeletePerson);
private void AddPerson()
{
Database.InsertPerson(SelectedPerson);
People.Add(new Person { Id = SelectedPerson.Id, Name = SelectedPerson.Name, Age = SelectedPerson.Age });
SelectedPerson = new Person();
}
private void UpdatePerson()
{
Database.UpdatePerson(SelectedPerson);
var person = People.FirstOrDefault(p => p.Id == SelectedPerson.Id);
if (person != null)
{
person.Name = SelectedPerson.Name;
person.Age = SelectedPerson.Age;
}
}
private void DeletePerson()
{
Database.DeletePerson(SelectedPerson.Id);
People.Remove(SelectedPerson);
SelectedPerson = new Person();
}
}
}
5. Membuat Tampilan UI
Buka MainWindow.axaml
dan ubah dengan:
<Window xmlns="https://github.com/avaloniaui"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d"
Title="Avalonia CRUD SQLite"
Width="400" Height="400"
x:Class="AvaloniaCrudApp.Views.MainWindow"
xmlns:vm="clr-namespace:AvaloniaCrudApp.ViewModels">
<Window.DataContext>
<vm:MainViewModel/>
</Window.DataContext>
<Grid RowDefinitions="Auto,Auto,Auto,*,Auto">
<TextBox Text="{Binding SelectedPerson.Name, Mode=TwoWay}" PlaceholderText="Name"/>
<TextBox Grid.Row="1" Text="{Binding SelectedPerson.Age, Mode=TwoWay}" PlaceholderText="Age"/>
<StackPanel Grid.Row="2" Orientation="Horizontal" Spacing="5">
<Button Content="Add" Command="{Binding AddCommand}"/>
<Button Content="Update" Command="{Binding UpdateCommand}"/>
<Button Content="Delete" Command="{Binding DeleteCommand}"/>
</StackPanel>
<ListBox Grid.Row="3" Items="{Binding People}" SelectedItem="{Binding SelectedPerson}">
<ListBox.ItemTemplate>
<DataTemplate>
<TextBlock Text="{Binding Name}"/>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
</Grid>
</Window>
6. Menjalankan Aplikasi
Jalankan aplikasi dengan:
dotnet run
Sekarang, Anda memiliki aplikasi CRUD sederhana menggunakan Avalonia dan SQLite! 🚀