Xamarin.Forms - Working With LiteDB CRUD Operations

In this article, you will learn how to use LiteDB Database with CRUD Operations in Xamarin.Forms.

Introduction

 
Xamarin.Forms code runs on multiple platforms - each of which has its own filesystem. This means that reading and writing files is most easily done using the native file APIs on each platform. Alternatively, embedded resources are a simpler solution to distribute data files with an app.
Xamarin.Forms - Working With LiteDB CRUD Operations  
 
LiteDB
Xamarin.Forms - Working With LiteDB CRUD Operations
  1. LiteDB is a serverless database fully written in C# code.
  2. LiteDB stores documents in the BSON (Binary JSON) data format like MongoDB.
  3. LiteDB is a simple and fast NoSQL database. use to build Mobile, Desktop and small web applications.
Prerequisites
  • Visual Studio 2017 or Later (Windows or Mac)

Setting up a Xamarin.Forms Project

 
Start by creating a new Xamarin.Forms project. You’ll learn more by going through the steps yourself or download the source from here.
 
Visual Studio 2019 has more options in the opening window. Clone or check out the code from any repository or, open a project or solution for your computer. Now, you need to click "Create a new project".
 
Xamarin.Forms - Working With LiteDB CRUD Operations 
 
Now, filter by Project Type: Mobile
 
Choose the Mobile App (Xamarin. forms) project under C# and Mobile.
 
Name your app. You probably want your project and solution to use the same name as your app. Put it on your preferred location for projects and click "Create".
 
Now, select the blank app and target platforms - Android, iOS and Windows (UWP).
 
Subsequently, go to the solution. In there, you get all the files and sources of your project (.NET Standard). Now, select XAML page and double-click to open the MainPage.Xaml page.
 
You now have a basic Xamarin.Forms app. Click the "Play" button to try it out.
 

Setting up the User Interface

 
Go to MainPage.Xaml and write the following code.
 
MainPage.xaml
  1. <?xml version="1.0" encoding="utf-8" ?>  
  2. <ContentPage xmlns="http://xamarin.com/schemas/2014/forms"  
  3.              xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"  
  4.              xmlns:local="clr-namespace:XamarinLiteDB"  
  5.              x:Class="XamarinLiteDB.MainPage">  
  6.   
  7.     <StackLayout>  
  8.         <StackLayout>  
  9.             <StackLayout HorizontalOptions="Center" VerticalOptions="Start">  
  10.                 <Image x:Name="imgBanner" Source="banner.png" ></Image>  
  11.                 <Image Margin="0,0,0,10" HeightRequest="100" Source="liteDB.png" ></Image>  
  12.                 <Label Margin="0,0,0,10" Text="LiteDB" FontAttributes="Bold" FontSize="Large" TextColor="Gray" HorizontalTextAlignment="Center" ></Label>  
  13.                 <Entry x:Name="txtPersonId" Placeholder="PersonId Update and Delete"></Entry>  
  14.                 <Entry x:Name="txtName" Placeholder="Enter Person Name"></Entry>  
  15.                 <StackLayout  HorizontalOptions="CenterAndExpand" Orientation="Horizontal">  
  16.                     <Button x:Name="btnAdd" WidthRequest="200" Text="Add" Clicked="BtnAdd_Clicked" />  
  17.                     <Button x:Name="btnRead" WidthRequest="200" Text="Read" Clicked="BtnRead_Clicked" />  
  18.                 </StackLayout>  
  19.                 <StackLayout HorizontalOptions="CenterAndExpand" Orientation="Horizontal">  
  20.                     <Button x:Name="btnUpdate" WidthRequest="200" Text="Update" Clicked="BtnUpdate_Clicked" />  
  21.                     <Button x:Name="btnDelete" WidthRequest="200" Text="Delete" Clicked="BtnDelete_Clicked" />  
  22.                 </StackLayout>  
  23.                 <ListView x:Name="lstPersons">  
  24.                     <ListView.ItemTemplate>  
  25.                         <DataTemplate>  
  26.                             <TextCell Text="{Binding Name}" Detail="{Binding PersonId}"></TextCell>  
  27.                         </DataTemplate>  
  28.                     </ListView.ItemTemplate>  
  29.                 </ListView>  
  30.   
  31.             </StackLayout>  
  32.         </StackLayout>  
  33.     </StackLayout>  
  34.      
  35. </ContentPage>   
Click the "Play" button to try it out.
 
Xamarin.Forms - Working With LiteDB CRUD Operations 
 
NuGet Packages
 
Now, add the following NuGet Packages.
  • LiteDB
Add LiteDB NuGet
 
Go to Solution Explorer and select your solution. Right-click and select "Manage NuGet Packages for Solution". Search "LiteDB" and add the package. Remember to install it for .NET Standard project.
 
Xamarin.Forms - Working With LiteDB CRUD Operations 
 
Create a Model
 
In this step, you can create a model to create a table.
 
Person.cs
  1. namespace XamarinLiteDB  
  2. {  
  3.     public class Person  
  4.     {  
  5.         public int PersonId { getset; }  
  6.         public string Name { getset; }  
  7.     }  
  8. }  
Get Local File Path
 
Write the following code to get the local file path for storing the database in App.xaml.cs.
 
App.xaml.cs
  1. static LiteDBHelper db;  
  2.   
  3. public static LiteDBHelper LiteDB  
  4.         {  
  5.             get  
  6.             {  
  7.                 if (db == null)  
  8.                 {  
  9.                     db = new LiteDBHelper(Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "XamarinLiteDB.db"));  
  10.                 }  
  11.                 return db;  
  12.             }  
  13.         }  
Create a Table
 
In this step, write the following code to create a LiteCollection and create the table in LiteDBHelper.cs constructor.
 
LiteDBHelper.cs
  1. protected LiteCollection<Person> personCollection;  
  2.   
  3.         public LiteDBHelper(string dbPath)  
  4.         {  
  5.             using (var db = new LiteDatabase(dbPath))  
  6.             {  
  7.                 personCollection = db.GetCollection<Person>("Persons");  
  8.             }  
  9.                   
  10.         }  
Check Database 
 
If you need to explore your LiteDB database, download LiteDBViewer 
 
https://github.com/falahati/LiteDBViewer/releases 
 
Example 
 
Xamarin.Forms - Working With LiteDB CRUD Operations
 
Read All
 
Now, write the code to read all data from LiteDB Database.
 
LiteDBHelper.cs
  1. //Get All Persons  
  2.         public List<Person> GetAllPersons()  
  3.         {  
  4.             var persons= new List<Person>(personCollection.FindAll());  
  5.             return persons;  
  6.         }  
MainPage.Xaml.cs
  1. //Get All Persons  
  2.             var personList=App.LiteDB.GetAllPersons();  
  3.             if(personList.Count!=0)  
  4.             {  
  5.                 lstPersons.ItemsSource = personList;  
  6.             }  
Click the "Play" button to try it out.
 
Xamarin.Forms - Working With LiteDB CRUD Operations
 
Insert
 
Now, write the following code to insert data into LiteDB Database.
  1. //Add New Person  
  2.         public void AddPerson(Person person)  
  3.         {  
  4.             personCollection.Insert(person);  
  5.         }  
  6.   
  7. private void BtnAdd_Clicked(object sender, EventArgs e)  
  8.         {  
  9.             if (!string.IsNullOrEmpty(txtName.Text))  
  10.             {  
  11.                 Person person = new Person()  
  12.                 {  
  13.                     Name = txtName.Text  
  14.                 };  
  15.                 //Add New Person  
  16.                 App.LiteDB.AddPerson(person);  
  17.                 txtName.Text = string.Empty;  
  18.                 DisplayAlert("Success""Person Added""OK");  
  19.   
  20.                 //Get All Persons  
  21.                 var personList = App.LiteDB.GetAllPersons();  
  22.                 if (personList.Count != 0)  
  23.                 {  
  24.                     lstPersons.ItemsSource = personList;  
  25.                 }  
  26.             }  
  27.         }  
Click the "Play" button to try it out.
 
Xamarin.Forms - Working With LiteDB CRUD Operations
 
Read
 
Now, write the following code to read data from LiteDB Database.
  1. //Get Person  
  2.        public Person GetPerson(int personId)  
  3.        {  
  4.            var person = GetAllPersons().Where(a => a.PersonId == personId).FirstOrDefault();  
  5.            return person;  
  6.        }  
  7.   
  8.   
  9.  private void BtnRead_Clicked(object sender, EventArgs e)  
  10.        {  
  11.            if(!string.IsNullOrEmpty(txtPersonId.Text))  
  12.            {  
  13.               var person= App.LiteDB.GetPerson(Convert.ToInt32(txtPersonId.Text));  
  14.                if(person!=null)  
  15.                {  
  16.                    txtName.Text = person.Name;  
  17.                    DisplayAlert("Success""Person Name: "+person.Name, "OK");  
  18.                }  
  19.                else  
  20.                {  
  21.                    DisplayAlert("Faild""Person is not available""OK");  
  22.                }  
  23.            }  
  24.        }  
Click the "Play" button to try it out.

Xamarin.Forms - Working With LiteDB CRUD Operations 
 
Update
 
Now, write the following code to update data to LiteDB Database.
  1. //Update Person  
  2.         public void UpdatePerson(Person person)  
  3.         {  
  4.             personCollection.Update(person);  
  5.         }  
  6.   
  7.   
  8. private void BtnUpdate_Clicked(object sender, EventArgs e)  
  9.         {  
  10.             if (!string.IsNullOrEmpty(txtPersonId.Text))  
  11.             {  
  12.                 Person person = new Person()  
  13.                 {  
  14.                     PersonId = Convert.ToInt32(txtPersonId.Text),  
  15.                     Name = txtName.Text  
  16.                 };  
  17.   
  18.                 //Update person  
  19.                 App.LiteDB.UpdatePerson(person);  
  20.                 txtName.Text = string.Empty;  
  21.                 txtPersonId.Text = string.Empty;  
  22.                 DisplayAlert("Success""Person Updated""OK");  
  23.   
  24.                 //Get All Persons  
  25.                 var personList = App.LiteDB.GetAllPersons();  
  26.                 if (personList.Count != 0)  
  27.                 {  
  28.                     lstPersons.ItemsSource = personList;  
  29.                 }  
  30.             }  
  31.         }  
Click the "Play" button to try it out.

Xamarin.Forms - Working With LiteDB CRUD Operations 
 
Delete
 
Now, write the following code to delete data from LiteDB Database.
  1. //Delete Person  
  2.        public void DeletePerson(int personId)  
  3.        {  
  4.            personCollection.Delete(a => a.PersonId == personId);  
  5.        }  
  6.   
  7.   
  8.   
  9.   
  10. rivate void BtnDelete_Clicked(object sender, EventArgs e)  
  11.        {  
  12.            if(!string.IsNullOrEmpty(txtPersonId.Text))  
  13.            {  
  14.                //Delete Person  
  15.                App.LiteDB.DeletePerson(Convert.ToInt32(txtPersonId.Text));  
  16.                txtPersonId.Text = string.Empty;  
  17.                DisplayAlert("Warning""Person Deleted!""OK");  
  18.   
  19.                //Get All Persons  
  20.                var personList = App.LiteDB.GetAllPersons();  
  21.                if (personList.Count != 0)  
  22.                {  
  23.                    lstPersons.ItemsSource = personList;  
  24.                }  
  25.            }  
  26.   
  27.        }   
Click the "Play" button to try it out.

Xamarin.Forms - Working With LiteDB CRUD Operations 
 

Full code


LiteDBHelper.cs
  1. using LiteDB;  
  2. using System;  
  3. using System.Collections.Generic;  
  4. using System.Text;  
  5. using System.Linq;  
  6. namespace XamarinLiteDB  
  7. {  
  8.     public class LiteDBHelper  
  9.     {  
  10.         protected LiteCollection<Person> personCollection;  
  11.   
  12.         public LiteDBHelper(string dbPath)  
  13.         {  
  14.             using (var db = new LiteDatabase(dbPath))  
  15.             {  
  16.                 personCollection = db.GetCollection<Person>("Persons");  
  17.             }  
  18.                   
  19.         }  
  20.   
  21.         //Get All Persons  
  22.         public List<Person> GetAllPersons()  
  23.         {  
  24.             var persons= new List<Person>(personCollection.FindAll());  
  25.             return persons;  
  26.         }  
  27.   
  28.         //Add New Person  
  29.         public void AddPerson(Person person)  
  30.         {  
  31.             personCollection.Insert(person);  
  32.         }  
  33.   
  34.         //Update Person  
  35.         public void UpdatePerson(Person person)  
  36.         {  
  37.             personCollection.Update(person);  
  38.         }  
  39.   
  40.         //Get Person  
  41.         public Person GetPerson(int personId)  
  42.         {  
  43.             var person = GetAllPersons().Where(a => a.PersonId == personId).FirstOrDefault();  
  44.             return person;  
  45.         }  
  46.         //Delete Person  
  47.         public void DeletePerson(int personId)  
  48.         {  
  49.             personCollection.Delete(a => a.PersonId == personId);  
  50.         }  
  51.   
  52.     }  
  53. }  
MainPage.Xaml.cs
  1. using Xamarin.Forms;  
  2.   
  3. namespace XamarinLiteDB  
  4. {  
  5.     public partial class MainPage : ContentPage  
  6.     {  
  7.         public MainPage()  
  8.         {  
  9.             InitializeComponent();  
  10.   
  11.             //Get All Persons  
  12.             var personList=App.LiteDB.GetAllPersons();  
  13.             if(personList.Count!=0)  
  14.             {  
  15.                 lstPersons.ItemsSource = personList;  
  16.             }  
  17.         }  
  18.   
  19.         private void BtnAdd_Clicked(object sender, EventArgs e)  
  20.         {  
  21.             if (!string.IsNullOrEmpty(txtName.Text))  
  22.             {  
  23.                 Person person = new Person()  
  24.                 {  
  25.                     Name = txtName.Text  
  26.                 };  
  27.                 //Add New Person  
  28.                 App.LiteDB.AddPerson(person);  
  29.                 txtName.Text = string.Empty;  
  30.                 DisplayAlert("Success""Person Added""OK");  
  31.   
  32.                 //Get All Persons  
  33.                 var personList = App.LiteDB.GetAllPersons();  
  34.                 if (personList.Count != 0)  
  35.                 {  
  36.                     lstPersons.ItemsSource = personList;  
  37.                 }  
  38.             }  
  39.         }  
  40.   
  41.         private void BtnRead_Clicked(object sender, EventArgs e)  
  42.         {  
  43.             if(!string.IsNullOrEmpty(txtPersonId.Text))  
  44.             {  
  45.                var person= App.LiteDB.GetPerson(Convert.ToInt32(txtPersonId.Text));  
  46.                 if(person!=null)  
  47.                 {  
  48.                     txtName.Text = person.Name;  
  49.                     DisplayAlert("Success""Person Name: "+person.Name, "OK");  
  50.                 }  
  51.                 else  
  52.                 {  
  53.                     DisplayAlert("Faild""Person is not available""OK");  
  54.                 }  
  55.             }  
  56.         }  
  57.   
  58.         private void BtnUpdate_Clicked(object sender, EventArgs e)  
  59.         {  
  60.             if (!string.IsNullOrEmpty(txtPersonId.Text))  
  61.             {  
  62.                 Person person = new Person()  
  63.                 {  
  64.                     PersonId = Convert.ToInt32(txtPersonId.Text),  
  65.                     Name = txtName.Text  
  66.                 };  
  67.   
  68.                 //Update person  
  69.                 App.LiteDB.UpdatePerson(person);  
  70.                 txtName.Text = string.Empty;  
  71.                 txtPersonId.Text = string.Empty;  
  72.                 DisplayAlert("Success""Person Updated""OK");  
  73.   
  74.                 //Get All Persons  
  75.                 var personList = App.LiteDB.GetAllPersons();  
  76.                 if (personList.Count != 0)  
  77.                 {  
  78.                     lstPersons.ItemsSource = personList;  
  79.                 }  
  80.             }  
  81.         }  
  82.   
  83.         private void BtnDelete_Clicked(object sender, EventArgs e)  
  84.         {  
  85.             if(!string.IsNullOrEmpty(txtPersonId.Text))  
  86.             {  
  87.                 //Delete Person  
  88.                 App.LiteDB.DeletePerson(Convert.ToInt32(txtPersonId.Text));  
  89.                 txtPersonId.Text = string.Empty;  
  90.                 DisplayAlert("Warning""Person Deleted!""OK");  
  91.   
  92.                 //Get All Persons  
  93.                 var personList = App.LiteDB.GetAllPersons();  
  94.                 if (personList.Count != 0)  
  95.                 {  
  96.                     lstPersons.ItemsSource = personList;  
  97.                 }  
  98.             }  
  99.   
  100.         }  
  101.   
  102.           
  103.     }  
  104. }   
I hope you have understood how to use LiteDB Database and perform CRUD operations in Xamarin.Forms. Thanks for reading. Please share your comments and feedback.
 
Happy Coding :)