|
Como acessar um banco SQLite num projeto multi-plataforma
Primeira coisa, adicione os pacotes corretos para cada projeto. Veja aqui.
Projeto

Persistencia
Produto.cs
using System;
using SQLite.Net.Attributes;
namespace Persistencia
{
[Table ("tb_produto")]
public class Produto
{
[PrimaryKey, AutoIncrement]
public int Id {
get;
set;
}
public string Nome {
get;
set;
}
[Column("vl_venda")]
public decimal Valor {
get;
set;
}
public Produto ()
{
}
}
}
DAL.cs
using System;
using System.Linq;
using System.Collections.Generic;
using Xamarin.Forms;
using System.Threading.Tasks;
using System.Collections;
namespace Persistencia
{
public class DAL : IDisposable
{
private SQLite.Net.SQLiteConnection _conexao;
public DAL ()
{
var config = DependencyService.Get<IConfig> ();
_conexao = new SQLite.Net.SQLiteConnection (config.Plataforma, System.IO.Path.Combine (config.DiretorioDB, "banco.db3"));
_conexao.CreateTable<Produto> ();
}
public void Gravar (Produto prod)
{
if (prod.Id == 0)
_conexao.Insert (prod);
else
_conexao.Update (prod);
}
public void GravarList (IEnumerable lista)
{
_conexao.InsertAll (lista);
}
public void Delete (Produto prod)
{
_conexao.Delete (prod);
}
public Produto GetId (int id)
{
return _conexao.Table<Produto> ().FirstOrDefault (p => p.Id == id);
}
public List<Produto> Get ()
{
return _conexao.Table<Produto> ().OrderBy (p => p.Nome).ToList();
}
public void Dispose ()
{
_conexao.Dispose ();
}
public void StartTransaction()
{
if (!_conexao.IsInTransaction)
_conexao.BeginTransaction ();
}
public void Commit()
{
if (!_conexao.IsInTransaction)
throw new Exception ("Nã estám transaçã");
else
_conexao.Commit ();
}
public void RollBack()
{
if (!_conexao.IsInTransaction)
throw new Exception ("Nã estám transaçã");
else
_conexao.Rollback ();
}
}
}
IConfig.cs
using System;
using SQLite.Net.Interop;
namespace Persistencia
{
public interface IConfig
{
string DiretorioDB { get; }
ISQLitePlatform Plataforma { get; }
}
}
Vendas - Projeto PCL
ClientesView.cs (consulta)
using System;
using Xamarin.Forms;
using Persistencia;
using System.Diagnostics;
namespace Vendas
{
public class ClientesView : ContentPage
{
private ListView lista;
public ClientesView ()
{
Title = "Consulta de Clientes";
NavigationPage.SetTitleIcon(this, null);
this.Appearing += Mostrar;
ToolbarItem menu1 = new ToolbarItem ();
menu1.Text = "Novo";
menu1.Order = ToolbarItemOrder.Primary; // para menu pelo botã de hardware use Secundary
menu1.Clicked += ToolBarClicked;
this.ToolbarItems.Add (menu1);
lista = new ListView ();
lista.RowHeight = 60;
lista.ItemTemplate = new DataTemplate (typeof(ProdutoViewCell));
lista.ItemTapped += Tapped;
StackLayout layout = new StackLayout ();
layout.Children.Add (lista);
Content = layout;
}
// evento que ocorre quando a tela se torna ativa
private void Mostrar(object sender, EventArgs e)
{
using (var dados = new DAL ()) {
lista.ItemsSource = dados.Get ();
}
}
private async void ToolBarClicked(object sender, EventArgs e)
{
var page = new ClientesCadastroView(new Produto());
await Navigation.PushAsync (page);
}
private async void Tapped (object sender, ItemTappedEventArgs e)
{
Produto prod = (Produto)e.Item;
var page = new ClientesCadastroView(prod);
await Navigation.PushAsync (page);
((ListView)sender).SelectedItem = null; // de-select the row
}
}
}
ClientesCadastroView.cs - cadastro
using System;
using Xamarin.Forms;
using Persistencia;
namespace Vendas
{
public class ClientesCadastroView : ContentPage
{
private Label lbId;
private Entry edNome;
private Entry edValor;
private Button btGravar;
private Button btExcluir;
public ClientesCadastroView (Produto prod)
{
Title = "Cadastro de Clientes";
NavigationPage.SetTitleIcon(this, null);
lbId = new Label ();
lbId.IsVisible = false;
edNome = new Entry ();
edNome.Placeholder = "nome";
edValor = new Entry ();
edValor.Placeholder = "valor";
btGravar = new Button ();
btGravar.Text = "Gravar";
btGravar.HorizontalOptions = LayoutOptions.StartAndExpand;
btGravar.Clicked += Gravar;
btExcluir = new Button ();
btExcluir.Text = "Excluir";
btExcluir.Clicked += Excluir;
btExcluir.HorizontalOptions = LayoutOptions.EndAndExpand;
btExcluir.IsVisible = false;
StackLayout lay = new StackLayout ();
lay.Children.Add (lbId);
lay.Children.Add (edNome);
lay.Children.Add (edValor);
StackLayout botoes = new StackLayout ();
botoes.Orientation = StackOrientation.Horizontal;
botoes.Children.Add (btGravar);
botoes.Children.Add (btExcluir);
lay.Children.Add (botoes);
// se tem dados jáarrega
if (prod.Id > 0)
{
lbId.Text = prod.Id.ToString ();
lbId.IsVisible = true;
lbId.IsEnabled = false;
edNome.Text = prod.Nome;
edValor.Text = prod.Valor.ToString ("N");
btExcluir.IsVisible = true;
}
edNome.Focus ();
Content = lay;
}
private void Gravar (object sender, EventArgs evt)
{
if (edNome.Text == "") {
DisplayAlert ("Erro", "Falta Nome", "Ok");
edNome.Focus ();
return;
}
if (edValor.Text == "") {
DisplayAlert ("Erro", "Falta valor", "Ok");
edValor.Focus ();
return;
}
var prod = new Produto ();
try {
prod.Id = int.Parse ("0" + lbId.Text);
prod.Nome = edNome.Text;
prod.Valor = decimal.Parse (edValor.Text);
using (var dal = new DAL ()) {
dal.Gravar (prod);
}
} catch (Exception e) {
DisplayAlert ("Erro", e.Message, "Ok");
}
// volta para páina anterior
Navigation.PopAsync();
}
private async void Excluir (object sender, EventArgs evt)
{
var resposta = await DisplayAlert ("Atençã", "Excluir o produto?", "Sim", "Nã");
string msg = string.Empty;
if (!resposta)
return;
var prod = new Produto ();
try {
prod.Id = int.Parse (lbId.Text);
using (var dal = new DAL ()) {
dal.Delete (prod);
}
} catch (Exception e) {
msg = e.Message;
}
if (!string.IsNullOrEmpty(msg))
await DisplayAlert ("Erro", msg, "Ok");
// volta para páina anterior
await Navigation.PopAsync();
}
}
}
Android
Config.cs
using System;
using Persistencia;
using SQLite.Net.Interop;
// injeçã de dependencia
[assembly: Dependency (typeof(Vendas.Droid.Config))]
namespace Vendas.Droid
{
public class Config : IConfig
{
// path para o Android
private string _diretorio;
public string DiretorioDB {
get {
// nã existe? cria
if (string.IsNullOrEmpty (_diretorio)) {
_diretorio = System.Environment.SpecialFolder.Personal.ToString ();
}
return _diretorio;
}
}
// classe que tem todo gerenciamento para Android
private ISQLitePlatform _plataforma;
public ISQLitePlatform Plataforma {
get {
// nã existe? cria
if (_plataforma == null) {
_plataforma = SQLite.Net.Platform.XamarinAndroid.SQLitePlatformAndroid ();
}
return _plataforma;
}
}
public Config ()
{
}
}
}
|