Search This Blog

Tuesday 3 May 2022

Performing CRUD Operation In .Net MAUI (SQLite) Using MVVM



Youtube Video:


Packages Required 
Install sqlite-net-pcl  Package in your .Net MAUI Project.









Create EmployeeModel with few properties & create EmployeeService.cs Class and add logic related to adding/updating and deleting employee code.

EmployeeModel.cs
using SQLite;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
 
namespace CrudOperationMaui.Models
{
    public class EmployeeModel
    {
        [PrimaryKey, AutoIncrement]
        public int ID { get; set; }
        public string Name { get; set; }
        public string Email { get; set; }
        public string Address { get; set; }
    }
} 
EmployeeService.cs
using CrudOperationMaui.Models;
using SQLite;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
 
namespace CrudOperationMaui.Services
{
    public class EmployeeService
    {
 
        private readonly SQLiteConnection _dbConnection;
        public EmployeeService()
        {
 
            string dbPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "Employee.db3");
            _dbConnection = new SQLiteConnection(dbPath);
            _dbConnection.CreateTable<EmployeeModel>();
 
        }
 
        public List<EmployeeModel> GetAllEmployees()
        {
            var res = _dbConnection.Table<EmployeeModel>().ToList();
            return res;
        }
 
        public int InsertEmployee(EmployeeModel obj)
        {
            return _dbConnection.Insert(obj);
        }
 
        public int UpdateEmployee(EmployeeModel obj)
        {
            return _dbConnection.Update(obj);
        }
 
        public int DeleteEmployee(EmployeeModel obj)
        {
            return _dbConnection.Delete(obj);
        }
    }
}
 


Now create UI For Displaying all employee details.

ShowEmployeePage.xaml (Design)
<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://schemas.microsoft.com/dotnet/2021/maui"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             x:Class="CrudOperationMaui.ShowEmployeePage"
             xmlns:viewmodels="clr-namespace:CrudOperationMaui.ViewModels"
             x:DataType="viewmodels:ShowEmployeePageViewModel"
             xmlns:models="clr-namespace:CrudOperationMaui.Models"
             Title="Show Employee">
    <VerticalStackLayout Padding="10,0,10,0">
        <Button Text="Add New Record" HorizontalOptions="Start" Command="{Binding NavigateToAddEmployeePageCommand}"/>
 
        <Grid Margin="0,5,0,5" RowDefinitions="Auto" ColumnDefinitions="33*,33*,33*">
            <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>
 
        <CollectionView  ItemsSource="{Binding Employees}"  >
            <CollectionView.ItemTemplate>
                <DataTemplate x:DataType="models:EmployeeModel">
                    <Grid RowSpacing="0" RowDefinitions="10,Auto,10,0.5" ColumnDefinitions="33*,33*,33*" VerticalOptions="FillAndExpand">
                        <Label  Text="{Binding Name}" Grid.Row="1" Grid.Column="0" />
                        <Label  Text="{Binding Email}" Grid.Row="1" Grid.Column="1" />
                        <Label  Text="{Binding Address}" Grid.Row="1" Grid.Column="2" />
                        <BoxView  BackgroundColor="Black"  Grid.Row="3" Grid.Column="0" Grid.ColumnSpan="3" />
                        <Grid.GestureRecognizers>
                            <TapGestureRecognizer Command="{Binding Source={x:RelativeSource AncestorType={x:Type viewmodels:ShowEmployeePageViewModel}},Path=SelectedEmployeeCommand}"  CommandParameter="{Binding .}" />
                        </Grid.GestureRecognizers>
                    </Grid>
                </DataTemplate>
            </CollectionView.ItemTemplate>
        </CollectionView>
    </VerticalStackLayout>
</ContentPage>
 


ShowEmployeePage.xaml.cs (Code Behind)
using CrudOperationMaui.Models;
using CrudOperationMaui.Services;
using CrudOperationMaui.ViewModels;
 
namespace CrudOperationMaui;
 
public partial class ShowEmployeePage : ContentPage
{
    private ShowEmployeePageViewModel _viewModel;
    public ShowEmployeePage()
	{
		InitializeComponent();
        _viewModel = new ShowEmployeePageViewModel();
        this.BindingContext = _viewModel;
    }
 
    protected override void OnAppearing()
    {
        base.OnAppearing();
        _viewModel.ShowEmployee();
    }
 
}
ShowEmployeePageViewModel (ViewModel)
using CrudOperationMaui.Models;
using CrudOperationMaui.Services;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Input;
 
namespace CrudOperationMaui.ViewModels
{
    public class ShowEmployeePageViewModel : BaseViewModel
    {
        #region Properties
 
        public ObservableCollection<EmployeeModel> Employees { get; set; } = new ObservableCollection<EmployeeModel>();
        private readonly EmployeeService _employeeService;
        #endregion
 
        #region Constructor
        public ShowEmployeePageViewModel()
        {
            _employeeService = new EmployeeService();
        }
        #endregion
 
        #region Methods
        public void ShowEmployee()
        {
            var allEmployees = _employeeService.GetAllEmployees();
 
            if (allEmployees?.Count > 0)
            {
                Employees.Clear();
                foreach (var employee in allEmployees)
                {
                    Employees.Add(employee);
                }
            }
        }
        #endregion
 
 
        #region Commands
        public ICommand NavigateToAddEmployeePageCommand => new Command(async () =>
        {
            await App.Current.MainPage.Navigation.PushAsync(new AddEmployeePage());
        });
 
 
        public ICommand SelectedEmployeeCommand => new Command<EmployeeModel>(async (employee) =>
        {
            string res = await App.Current.MainPage.DisplayActionSheet("Operation", "Cancel", null, "Update", "Delete");
 
            switch (res)
            {
                case "Update":
                    await App.Current.MainPage.Navigation.PushAsync(new AddEmployeePage(employee));
                    break;
                case "Delete":
                    int del = _employeeService.DeleteEmployee(employee);
                    if (del > 0)
                    {
                        Employees.Remove(employee);
                    }
                    break;
            }
        });
        #endregion
 
    }
}
 


Now create UI For Adding/Updating specific employee details.

AddEmployeePage.xaml (Design)
<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://schemas.microsoft.com/dotnet/2021/maui"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             x:Class="CrudOperationMaui.AddEmployeePage"
             xmlns:viewmodels="clr-namespace:CrudOperationMaui.ViewModels"
             x:DataType="viewmodels:AddEmployeePageViewModel"
             Title="AddEmployeePage">
    <VerticalStackLayout Padding="10,0,10,0" VerticalOptions="StartAndExpand" HorizontalOptions="FillAndExpand">
        <Entry Text="{Binding Name}" Placeholder="Enter Name" />
        <Entry Text="{Binding Email}" Placeholder="Enter Email" />
        <Entry Text="{Binding Address}" Placeholder="Enter Address" />
        <Button x:Name="btnSaveUpdate" Text="Save" Command="{Binding AddEmployeeCommand}" />
    </VerticalStackLayout>
</ContentPage>
 
AddEmployeePage.xaml.cs (Code Behind)
using CrudOperationMaui.Models;
using CrudOperationMaui.Services;
using CrudOperationMaui.ViewModels;
 
namespace CrudOperationMaui;
 
public partial class AddEmployeePage : ContentPage
{
    public AddEmployeePage()
    {
        InitializeComponent();
        this.BindingContext = new AddEmployeePageViewModel();
    }
 
 
    public AddEmployeePage(EmployeeModel obj)
    {
        InitializeComponent();
        this.BindingContext = new AddEmployeePageViewModel(obj);
    }
 
 
}

AddEmployeePageViewModel.cs (View Model)
using CrudOperationMaui.Models;
using CrudOperationMaui.Services;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Input;
 
namespace CrudOperationMaui.ViewModels
{
    public class AddEmployeePageViewModel : BaseViewModel
    {
        #region Properties
        private string _name;
        public string Name
        {
            get => _name;
            set => SetProperty(ref _name, value);
        }
 
        private string _email;
        public string Email
        {
            get => _email;
            set => SetProperty(ref _email, value);
        }
 
        private string _address;
        public string Address
        {
            get => _address;
            set => SetProperty(ref _address, value);
        }
 
        private int _employeeID;
        private readonly EmployeeService _employeeService;
        #endregion
 
        #region Constructor
        public AddEmployeePageViewModel()
        {
            _employeeService = new EmployeeService();
        }
 
        public AddEmployeePageViewModel(EmployeeModel employeeObj)
        {
            Name = employeeObj.Name;
            Email = employeeObj.Email;
            Address = employeeObj.Address;
            _employeeID = employeeObj.ID;
            _employeeService = new EmployeeService();
 
        }
        #endregion
 
 
        #region Commands
        public ICommand AddEmployeeCommand => new Command(async () =>
        {
            EmployeeModel obj = new EmployeeModel
            {
                Email = Email,
                Address = Address,
                Name = Name,
                ID = _employeeID,
            };
            if (_employeeID > 0)
            {
                _employeeService.UpdateEmployee(obj);
            }
            else
            {
                _employeeService.InsertEmployee(obj);
            }
            await App.Current.MainPage.Navigation.PopAsync();
        });
        #endregion
 
    }
}
 

Write Following code on App.xaml.cs to Navigate to ShowEmployeePage.

App.xaml.cs
namespace CrudOperationMaui;
 
public partial class App : Application
{
	public App()
	{
		InitializeComponent();
 
		MainPage = new NavigationPage(new ShowEmployeePage());
	}
}
 

2 comments:

  1. Doesn't work, tutorial is incomplete and missing several crucial parts.

    ReplyDelete
  2. Here is a blog post how to implement CRUD in MAUI with SQLite and EFCore: https://community.devexpress.com/blogs/mobile/archive/2023/10/18/incorporate-crud-operations-into-your-app-with-devexpress-net-maui-collectionview.aspx

    ReplyDelete

Popular Posts