Xamarin Forms - SQLite : CRUD com Entity Framework Core 3.1 - II


Neste artigo vamos usar os recursos do EF Core 3.1 para acessar dados no SQLite em uma aplicação Xamarin Forms e realizar um CRUD básico usando o Visual Studio 2019 e a linguagem C#.

Vamos continuar o artigo anterior implementando as demais View Models e Views do projeto para realizar o CRUD no SQLite com EF Core.

Editando os dados de Times : EditTimePage.xaml e EditTimeViewModel.cs

Vamos criar o arquivo EditTimePage.xaml para editar os dados dos times:

<?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:d="http://xamarin.com/schemas/2014/forms/design"
             xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
             mc:Ignorable="d"
             x:Class="XF_Crud1.Views.EditTimePage"
             Title="Alterar Time">
    <ContentPage.ToolbarItems>
        <ToolbarItem Text="Salvar"
                     Icon="ic_save.png"
                     Command="{Binding SaveTimeCommand}" />
    </ContentPage.ToolbarItems>
    
    <ContentPage.Content>
        <StackLayout>
            <Entry Placeholder="Nome do time"
                   Text="{Binding Nome}"
                   Margin="4" />
            <Entry Placeholder="Nome do treinador"
                   Text="{Binding Treinador}"
                   Margin="4" />
            <Entry Placeholder="Nome da cidade"
                   Text="{Binding Cidade}"
                   Margin="4" />
            <Entry Placeholder="Nome do estádio"
                   Text="{Binding Estadio}"
                   Margin="4" />
        </StackLayout>
    </ContentPage.Content>
</ContentPage
 

A seguir vamos criar a ViewModel EditTimeViewModel.cs :

using System.Windows.Input;
using Xamarin.Forms;
using XF_Crud1.DataAccess;
using XF_Crud1.Helpers;
namespace XF_Crud1.ViewModels
{
    public class EditTimeViewModel : BaseViewModel
    {
        private string nome;
        public string Nome
        {
            get { return nome; }
            set
            {
                nome = value;
                OnPropertyChanged();
            }
        }
        private string treinador;
        public string Treinador
        {
            get { return treinador; }
            set
            {
                treinador = value;
                OnPropertyChanged();
            }
        }
        private string cidade;
        public string Cidade
        {
            get { return cidade; }
            set
            {
                cidade = value;
                OnPropertyChanged();
            }
        }
        private string estadio;
        public string Estadio
        {
            get { return estadio; }
            set
            {
                estadio = value;
                OnPropertyChanged();
            }
        }
        public ICommand SaveTimeCommand { get; private set; }
        private int _timeId;
        private AppDbContext _context;
        public EditTimeViewModel(int timeId)
        {
            _context = new AppDbContext();
            var time = _context.Times.Find(timeId);
            _timeId = time.TimeId;
            Nome = time.Nome;
            Treinador = time.Treinador;
            Estadio = time.Estadio;
            Cidade = time.Cidade;
            SaveTimeCommand = new Command(SaveTime);
        }
        async void SaveTime()
        {
            var time = _context.Times.Find(_timeId);
            time.Nome = Nome;
            time.Treinador = Treinador;
            time.Estadio = Estadio;
            time.Cidade = Cidade;
            _context.Times.Update(time);
            _context.SaveChanges();
            await Application.Current.MainPage.Navigation.PopAsync();
        }
    }
}

Incluindo um novo jogador no time: AddJogadorPage.xaml e AddJogadorViewModel.cs

No arquivo AddJogadorPage temos o código que inclui um novo jogador:

<?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:d="http://xamarin.com/schemas/2014/forms/design"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    mc:Ignorable="d"
    x:Class="XF_Crud1.Views.AddJogadorPage"
    Title="Incluir Jogador">
    <ContentPage.ToolbarItems>
        <ToolbarItem Text="Salvar"
                     Icon="ic_save.png"
                     Command="{Binding SaveJogadorCommand}" />
    </ContentPage.ToolbarItems>
    
    <ContentPage.Content>
        <StackLayout>
            <Label Text="{Binding Nome, StringFormat='Novo jogador para : {0}'}"
                   Margin="4,12,4,4" />
            <Entry Placeholder="Nome do jogador"
                   Text="{Binding Nome}"
                   Margin="4" />
            <Entry Placeholder="Posição"
                   Text="{Binding Posicao}"
                   Margin="4" />
        </StackLayout>
    </ContentPage.Content>
</ContentPage>

A seguir a view model AddJogadorViewModel :

using System.Linq;
using System.Windows.Input;
using Xamarin.Forms;
using XF_Crud1.DataAccess;
using XF_Crud1.Helpers;
using XF_Crud1.Models;
namespace XF_Crud1.ViewModels
{
    public class AddJogadorViewModel : BaseViewModel
    {
        private string nomeTime;
        public string NomeTime
        {
            get { return nomeTime; }
            set
            {
                nomeTime = value;
                OnPropertyChanged();
            }
        }
        private string nome;
        public string Nome
        {
            get { return nome; }
            set
            {
                nome = value;
                OnPropertyChanged();
            }
        }
        private string posicao;
        public string Posicao
        {
            get { return posicao; }
            set
            {
                posicao = value;
                OnPropertyChanged();
            }
        }
        public ICommand SaveJogadorCommand { get; private set; }
        private int _timeId;
        private AppDbContext _context;
        public AddJogadorViewModel(int timeId)
        {
            _timeId = timeId;
            _context = new AppDbContext();
            var time = _context.Times.Where(t => t.TimeId == timeId).FirstOrDefault();
            NomeTime = time.Nome;
            SaveJogadorCommand = new Command(SaveJogador);
        }
        void SaveJogador()
        {
            var time = _context.Times.Where(t => t.TimeId == _timeId).FirstOrDefault();
            Jogador player = new Jogador()
            {
                Nome = Nome,
                Posicao = Posicao,
                TimeId = _timeId
            };
            _context.Jogadores.Add(player);
            _context.SaveChanges();
            Application.Current.MainPage.Navigation.PopAsync();
        }
    }
}

Editando dados de jogador do time: EditJogadorPage.xaml e EditJogadorViewModel.cs

Agora vamos editar dados na view EditJogadorPage:

<?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:d="http://xamarin.com/schemas/2014/forms/design"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    mc:Ignorable="d"
    x:Class="XF_Crud1.Views.EditJogadorPage"
    Title="Alterar Jogador">

    <ContentPage.ToolbarItems>
        <ToolbarItem Text="Salvar"
                     Icon="ic_save.png"
                     Command="{Binding SaveJogadorCommand}" />
    </ContentPage.ToolbarItems>
    <ContentPage.Content>
        <StackLayout>
            <Label Text="{Binding NomeTime, StringFormat='Jogando por : {0}'}"
                   Margin="4,12,4,4" />
            <Entry Placeholder="Nome"
                   Text="{Binding Nome}"
                   Margin="4" />
            <Entry Placeholder="Posição"
                   Text="{Binding Posicao}"
                   Margin="4" />
       </StackLayout>
    </ContentPage.Content>
</ContentPage>

A seguir a view model EditJogadorViewModel :

using Microsoft.EntityFrameworkCore;
using System.Linq;
using System.Windows.Input;
using Xamarin.Forms;
using XF_Crud1.DataAccess;
using XF_Crud1.Helpers;
namespace XF_Crud1.ViewModels
{
    public class EditJogadorViewModel : BaseViewModel
    {
        private string nomeTime;
        public string NomeTime
        {
            get { return nomeTime; }
            set
            {
                nomeTime = value;
                OnPropertyChanged();
            }
        }
        private string nome;
        public string Nome
        {
            get { return nome; }
            set
            {
                nome = value;
                OnPropertyChanged();
            }
        }
        private string posicao;
        public string Posicao
        {
            get { return posicao; }
            set
            {
                posicao = value;
                OnPropertyChanged();
            }
        }
        public ICommand SaveJogadorCommand { get; private set; }
        private int _jogadorId;
        private AppDbContext _context;
        public EditJogadorViewModel(int jogadorId)
        {
            _jogadorId = jogadorId;
            using (_context = new AppDbContext())
            {
                var jogadores = _context.Jogadores.ToList();
                var player = _context.Jogadores.Include(x => x.Time).SingleOrDefault(x => x.JogadorId == _jogadorId);
                NomeTime = player.Time.Nome;
                Nome = player.Nome;
                Posicao = player.Posicao;
                SaveJogadorCommand = new Command(SaveJogador);
            }
        }
        void SaveJogador()
        {
            using (_context = new AppDbContext())
            {
                var player = _context.Jogadores.Find(_jogadorId);
                player.Posicao = Posicao;
                player.Nome = Nome;
                _context.Jogadores.Update(player);
                _context.SaveChanges();
            }
            Application.Current.MainPage.Navigation.PopAsync();
        }
    }
}

 

Executando o projeto no Genymotion teremos o seguinte resultado:

Embora o código seja extenso o projeto é relativamente simples e pode ser alterado e incrementado de diversas formas.

Pegue o código do projeto aqui: XF_Crud1.zip (sem as referências)

"Quem ama a sua vida perdê-la-á, e quem neste mundo odeia a sua vida, guardá-la-á para a vida eterna.
Se alguém me serve, siga-me, e onde eu estiver, ali estará também o meu servo. E, se alguém me servir, meu Pai o honrará."
João 12:25,26

Referências:


José Carlos Macoratti