Olá, neste artigo irei demonstrar como você pode trabalhar com um Banco de Dados local em suas aplicações Xamarin.Forms.
Para este exemplo, escolhi o LiteDB que é um banco de dados NoSQL desenvolvido pelo brasileiro Mauricio David.
ADICIONANDO O NUGET PACKAGE
Clique com o botão direito em cima de sua Solution e selecione “Manage NuGet Packages for Solution…”.
Digite “LiteDB” e selecione o plugin como demonstrado na imagem a seguir.
Selecione o projeto compartilhado e clique no botão “Install”.
Preparando o LiteDB
Como o banco de dados é local, é necessário criar uma interface para pegar a pasta e o caminho do banco de dados.
Compartilhado
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
namespace DemoLiteDB | |
{ | |
public interface IHelper | |
{ | |
string GetFilePath(string file); | |
} | |
} |
Android
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.IO; | |
using DemoLiteDB.Droid; | |
using Xamarin.Forms; | |
[assembly: Dependency(typeof(Helper))] | |
namespace DemoLiteDB.Droid | |
{ | |
public class Helper : IHelper | |
{ | |
public string GetFilePath(string file) | |
{ | |
string path = Environment.GetFolderPath(Environment.SpecialFolder.Personal); | |
return Path.Combine(path, file); | |
} | |
} | |
} |
iOS
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using DemoLiteDB.iOS; | |
using System; | |
using System.IO; | |
using Xamarin.Forms; | |
[assembly: Dependency(typeof(Helper))] | |
namespace DemoLiteDB.iOS | |
{ | |
public class Helper : IHelper | |
{ | |
public string GetFilePath(string file) | |
{ | |
string document = Environment.GetFolderPath(Environment.SpecialFolder.Personal); | |
string library = Path.Combine(document, "..", "Library", "Databases"); | |
if (!Directory.Exists(library)) | |
{ | |
Directory.CreateDirectory(library); | |
} | |
return Path.Combine(library, file); | |
} | |
} | |
} |
Utilizando o LiteDB
Crie uma classe com as propriedades desejada, para este exemplo eu criei uma classe chamada Customer.cs como demonstrada a seguir.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
namespace DemoLiteDB | |
{ | |
public class Customer | |
{ | |
public int Id { get; set; } | |
public string Name { get; set; } | |
} | |
} |
Xaml
Adicione os seguintes controles
- Entry – Para utilizar a propriedade “Name” no método Insert e Get.
- Button Insert – Para inserir um novo customer com o nome digitado no Entry.
- Button Get – Para pegar o customer no BD que possui o name digitado no Entry.
- ListView – Para listar os customers cadastrados e quando um elemento selecionado poder realizar a exclusão.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?xml version="1.0" encoding="utf-8" ?> | |
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms" | |
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml" | |
xmlns:local="clr-namespace:DemoLiteDB" | |
x:Class="DemoLiteDB.MainPage" Title="Demo LiteDB"> | |
<StackLayout Padding="10"> | |
<Entry x:Name="EntryName" Placeholder="Name"/> | |
<Button Text="Insert" Clicked="Insert"/> | |
<Button Text="Get" Clicked="Get" /> | |
<ListView x:Name="ListCustomers" ItemSelected="List_Selected"> | |
<ListView.ItemTemplate> | |
<DataTemplate> | |
<ViewCell> | |
<StackLayout Orientation="Horizontal" Padding="10"> | |
<Label Text="{Binding Id}"></Label> | |
<Label Text="{Binding Name}"></Label> | |
</StackLayout> | |
</ViewCell> | |
</DataTemplate> | |
</ListView.ItemTemplate> | |
</ListView> | |
</StackLayout> | |
</ContentPage> |
C#
Verifica se o banco de dados já existe, caso não exista ele cria.
_dataBase = new LiteDatabase(DependencyService.Get<IHelper>().GetFilePath(“Banco.db“));
Realiza uma consulta de customers
Customers = _dataBase.GetCollection<Customer>();
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System.Linq; | |
using LiteDB; | |
using Xamarin.Forms; | |
namespace DemoLiteDB | |
{ | |
public partial class MainPage : ContentPage | |
{ | |
LiteDatabase _dataBase; | |
LiteCollection<Customer> Customers; | |
public MainPage() | |
{ | |
InitializeComponent(); | |
_dataBase = new LiteDatabase(DependencyService.Get<IHelper>().GetFilePath("Banco.db")); | |
Customers = _dataBase.GetCollection<Customer>(); | |
ListCustomers.ItemsSource = Customers.FindAll(); | |
BindingContext = this; | |
} | |
} | |
} |
Insert
Método para inserir um novo Customer
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
private void Insert(object sender, System.EventArgs e) | |
{ | |
int idCustomer = Customers.Count() == 0 ? 1 : (int) (Customers.Max(x => x.Id) + 1); | |
Customer customer = new Customer | |
{ | |
Id = idCustomer, | |
Name = EntryName.Text, | |
}; | |
Customers.Insert(customer); | |
ListCustomers.ItemsSource = Customers.FindAll(); | |
} |
Get
Método para pegar o primeiro customer que encontrar com o name igual ao digitado no Entry.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
private void Get(object sender, System.EventArgs e) | |
{ | |
Customers = _dataBase.GetCollection<Customer>(); | |
if (Customers.Count() > 0) | |
{ | |
var customer = Customers.FindAll().FirstOrDefault(x => x.Name == EntryName.Text); | |
DisplayAlert("id: " +customer?.Id, "Name: "+customer?.Name, "ok"); | |
} | |
} |
List_Selected
Método para quando selecionado um elemento da lista, caso a resposta seja “Sim” o elemento será deletado.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
private async void List_Selected(object sender, SelectedItemChangedEventArgs e) | |
{ | |
var action = await DisplayActionSheet("Atenção", "Não", "Sim", "Deletar ?"); | |
if (action == "Sim") | |
{ | |
var customer = e.SelectedItem as Customer; | |
Customers.Delete(customer?.Id); | |
ListCustomers.ItemsSource = Customers.FindAll(); | |
} | |
} |
Resultado
Para saber mais sobre o LiteDB acesse: Getting Started
Esse e todos os exemplos deste blog encontram-se disponíveis no GitHub.
Nice article! Should I switch to LiteDB from Sqlite? I write mostly Xamarin.Forms apps.
CurtirCurtir
Thanks! In legacy projects I think is not a good idea. But in new projects it’s a good option
CurtirCurtido por 1 pessoa