Search This Blog

Sunday 1 December 2019

Xamarin CRUD Operation With EntityFramework (SQLite)








Github URL : https://github.com/mistrypragnesh40/Crud_Demo_UsingSQLIte

Packages Required 




Configure Database
Create the class DatabaseContext that extends the DbContext class.

DatabaseContext.cs
using Crud_Demo_UsingSQLIte.Models;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
 
namespace Crud_Demo_UsingSQLIte
{
    public class DatabaseContext : DbContext
    {
        public DbSet<EmployeeModel> Employees { get; set; }
        public DatabaseContext()
        {
            this.Database.EnsureCreated();
        }
        // overrides the OnConfigure Method 
        protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
        {
            string dbPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Personal), "Employee.db");
            optionsBuilder.UseSqlite($"Filename={dbPath}");
        }
    }
}
 

Models
EmployeeModel.cs
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Text;
 
namespace Crud_Demo_UsingSQLIte.Models
{
    public class EmployeeModel
    {
        [Key]
        public int Id { get; set; }
        public string Name { get; set; }
        public string Email { get; set; }
        public string Address { get; set; }
    }
}
Services
EmployeeService.cs
using Crud_Demo_UsingSQLIte.Models;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Threading.Tasks;
 
namespace Crud_Demo_UsingSQLIte.Services
{
    public class EmployeeService
    {
        private DatabaseContext getContext()
        {
            return new DatabaseContext();
        }
 
        public async Task<List<EmployeeModel>> GetAllEmployees()
        {
            var _dbContext = getContext();
            var res = await _dbContext.Employees.ToListAsync();
            return res;
        }
 
        public async Task<int> UpdateEmployee(EmployeeModel obj)
        {
            var _dbContext = getContext();
            _dbContext.Employees.Update(obj);
            int c = await _dbContext.SaveChangesAsync();
            return c;
        }
 
        public int InsertEmployee(EmployeeModel obj)
        {
            var _dbContext = getContext();
            _dbContext.Employees.Add(obj);
            int c = _dbContext.SaveChanges();
            return c;
        }
 
        public int DeleteEmployee(EmployeeModel obj)
        {
 
            var _dbContext = getContext();
            _dbContext.Employees.Remove(obj);
            int c = _dbContext.SaveChanges();
            return c;
        }
    }
}
 
Implementation

App.xaml.cs
public App()
{
     InitializeComponent();
     MainPage = new NavigationPage(new ShowEmployeePage());
}
Views
ShowEmployeePage.xaml
<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             Title="Employee Details"
             x:Class="Crud_Demo_UsingSQLIte.Views.ShowEmployeePage">
    <ContentPage.Content>
        <StackLayout Margin="10" HorizontalOptions="FillAndExpand" VerticalOptions="FillAndExpand">
            <Button Text="Add New Record" x:Name="btnAddRecord"  HorizontalOptions="Start"  Clicked="btnAddRecord_Clicked" />
 
            <Grid>
                <Grid.RowDefinitions>
                    <RowDefinition Height="Auto"></RowDefinition>
                </Grid.RowDefinitions>
                <Grid.ColumnDefinitions>
                    <ColumnDefinition></ColumnDefinition>
                    <ColumnDefinition></ColumnDefinition>
                    <ColumnDefinition></ColumnDefinition>
                </Grid.ColumnDefinitions>
                <Label Text="Name"  FontAttributes="Bold" HorizontalTextAlignment="Start"  Grid.Row="0" Grid.Column="0" />
                <Label Text="Email" FontAttributes="Bold" HorizontalTextAlignment="Start" Grid.Row="0" Grid.Column="1" />
                <Label Text="Address" FontAttributes="Bold" HorizontalTextAlignment="Start" Grid.Row="0" Grid.Column="2" />
            </Grid>
            <ListView x:Name="lstData" HasUnevenRows="True" ItemSelected="lstData_ItemSelected" >
                <ListView.ItemTemplate>
                    <DataTemplate>
                        <ViewCell >
                            <Frame HorizontalOptions="FillAndExpand" VerticalOptions="FillAndExpand">
                                <Grid>
                                    <Grid.RowDefinitions>
                                        <RowDefinition Height="Auto"></RowDefinition>
                                    </Grid.RowDefinitions>
                                    <Grid.ColumnDefinitions>
                                        <ColumnDefinition></ColumnDefinition>
                                        <ColumnDefinition></ColumnDefinition>
                                        <ColumnDefinition></ColumnDefinition>
                                    </Grid.ColumnDefinitions>
                                    <Label Text="{Binding Name}"   Grid.Row="0" Grid.Column="0" />
                                    <Label Text="{Binding Email}" Grid.Row="0" Grid.Column="1" />
                                    <Label Text="{Binding Address}" Grid.Row="0" Grid.Column="2" />
                                </Grid>
                            </Frame>
                        </ViewCell>
                    </DataTemplate>
                </ListView.ItemTemplate>
            </ListView>
        </StackLayout>
    </ContentPage.Content>
</ContentPage>

ShowEmployeePage.xaml.cs
using Crud_Demo_UsingSQLIte.Models;
using Crud_Demo_UsingSQLIte.Services;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
 
using Xamarin.Forms;
using Xamarin.Forms.Xaml;
 
namespace Crud_Demo_UsingSQLIte.Views
{
    [XamlCompilation(XamlCompilationOptions.Compile)]
    public partial class ShowEmployeePage : ContentPage
    {
        EmployeeService services;
        public ShowEmployeePage()
        {
            InitializeComponent();
            services = new EmployeeService();
        }
        protected override void OnAppearing()
        {
            base.OnAppearing();
            showEmployee();
        }
        private void showEmployee()
        {
            var res = services.GetAllEmployees().Result;
            lstData.ItemsSource = res;
        }
 
        private void btnAddRecord_Clicked(object sender, EventArgs e)
        {
            this.Navigation.PushAsync(new AddEmployee());
        }
 
        private async void lstData_ItemSelected(object sender, SelectedItemChangedEventArgs e)
        {
            if (e.SelectedItem != null)
            {
                EmployeeModel obj = (EmployeeModel)e.SelectedItem;
                string res = await DisplayActionSheet("Operation", "Cancel", null, "Update", "Delete");
 
                switch (res)
                {
                    case "Update":
                        await this.Navigation.PushAsync(new AddEmployee(obj));
                        break;
                    case "Delete":
                        services.DeleteEmployee(obj);
                        showEmployee();
                        break;
                }
                lstData.SelectedItem = null;
            }
        }
    }
}
AddEmployee.xaml
<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             Title="Add/Update Employee"
             x:Class="Crud_Demo_UsingSQLIte.Views.AddEmployee">
    <ContentPage.Content>
        <StackLayout Margin="10" VerticalOptions="StartAndExpand" HorizontalOptions="FillAndExpand">
            <Entry x:Name="txtName" Placeholder="Enter Name" />
            <Entry x:Name="txtEmail" Placeholder="Enter Email" />
            <Entry x:Name="txtAddress" Placeholder="Enter Address" />
            <Button x:Name="btnSaveUpdate" Text="Save" Clicked="btnSaveUpdate_Clicked" />
        </StackLayout>
    </ContentPage.Content>
</ContentPage>
AddEmployee.xaml.cs
using Crud_Demo_UsingSQLIte.Models;
using Crud_Demo_UsingSQLIte.Services;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
 
using Xamarin.Forms;
using Xamarin.Forms.Xaml;
 
namespace Crud_Demo_UsingSQLIte.Views
{
    [XamlCompilation(XamlCompilationOptions.Compile)]
    public partial class AddEmployee : ContentPage
    {
        EmployeeService _services;
        bool _isUpdate;
        int employeeID;
        public AddEmployee()
        {
            InitializeComponent();
            _services = new EmployeeService();
            _isUpdate = false;
        }
        public AddEmployee(EmployeeModel obj)
        {
            InitializeComponent();
            _services = new EmployeeService();
            if (obj != null)
            {
                employeeID = obj.Id;
                txtName.Text = obj.Name;
                txtEmail.Text = obj.Email;
                txtAddress.Text = obj.Address;
                _isUpdate = true;
            }
        }
        private async void btnSaveUpdate_Clicked(object sender, EventArgs e)
        {
            EmployeeModel obj = new EmployeeModel();
            obj.Name = txtName.Text;
            obj.Email = txtEmail.Text;
            obj.Address = txtAddress.Text;
            if (_isUpdate)
            {
                obj.Id = employeeID;
                await _services.UpdateEmployee(obj);
            }
            else
            {
                _services.InsertEmployee(obj);
            }
            await this.Navigation.PopAsync();
        }
    }
}

1 comment:

Popular Posts