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. <StackLayout>
  7. <StackLayout>
  8. <StackLayout HorizontalOptions="Center" VerticalOptions="Start">
  9. <Image x:Name="imgBanner" Source="banner.png" ></Image>
  10. <Image Margin="0,0,0,10" HeightRequest="100" Source="liteDB.png" ></Image>
  11. <Label Margin="0,0,0,10" Text="LiteDB" FontAttributes="Bold" FontSize="Large" TextColor="Gray" HorizontalTextAlignment="Center" ></Label>
  12. <Entry x:Name="txtPersonId" Placeholder="PersonId Update and Delete"></Entry>
  13. <Entry x:Name="txtName" Placeholder="Enter Person Name"></Entry>
  14. <StackLayout HorizontalOptions="CenterAndExpand" Orientation="Horizontal">
  15. <Button x:Name="btnAdd" WidthRequest="200" Text="Add" Clicked="BtnAdd_Clicked" />
  16. <Button x:Name="btnRead" WidthRequest="200" Text="Read" Clicked="BtnRead_Clicked" />
  17. </StackLayout>
  18. <StackLayout HorizontalOptions="CenterAndExpand" Orientation="Horizontal">
  19. <Button x:Name="btnUpdate" WidthRequest="200" Text="Update" Clicked="BtnUpdate_Clicked" />
  20. <Button x:Name="btnDelete" WidthRequest="200" Text="Delete" Clicked="BtnDelete_Clicked" />
  21. </StackLayout>
  22. <ListView x:Name="lstPersons">
  23. <ListView.ItemTemplate>
  24. <DataTemplate>
  25. <TextCell Text="{Binding Name}" Detail="{Binding PersonId}"></TextCell>
  26. </DataTemplate>
  27. </ListView.ItemTemplate>
  28. </ListView>
  29. </StackLayout>
  30. </StackLayout>
  31. </StackLayout>
  32. </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 { get; set; }
  6. public string Name { get; set; }
  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. public static LiteDBHelper LiteDB
  3. {
  4. get
  5. {
  6. if (db == null)
  7. {
  8. db = new LiteDBHelper(Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "XamarinLiteDB.db"));
  9. }
  10. return db;
  11. }
  12. }
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. public LiteDBHelper(string dbPath)
  3. {
  4. using (var db = new LiteDatabase(dbPath))
  5. {
  6. personCollection = db.GetCollection<Person>("Persons");
  7. }
  8. }
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. private void BtnAdd_Clicked(object sender, EventArgs e)
  7. {
  8. if (!string.IsNullOrEmpty(txtName.Text))
  9. {
  10. Person person = new Person()
  11. {
  12. Name = txtName.Text
  13. };
  14. //Add New Person
  15. App.LiteDB.AddPerson(person);
  16. txtName.Text = string.Empty;
  17. DisplayAlert("Success", "Person Added", "OK");
  18. //Get All Persons
  19. var personList = App.LiteDB.GetAllPersons();
  20. if (personList.Count != 0)
  21. {
  22. lstPersons.ItemsSource = personList;
  23. }
  24. }
  25. }
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. private void BtnRead_Clicked(object sender, EventArgs e)
  8. {
  9. if(!string.IsNullOrEmpty(txtPersonId.Text))
  10. {
  11. var person= App.LiteDB.GetPerson(Convert.ToInt32(txtPersonId.Text));
  12. if(person!=null)
  13. {
  14. txtName.Text = person.Name;
  15. DisplayAlert("Success", "Person Name: "+person.Name, "OK");
  16. }
  17. else
  18. {
  19. DisplayAlert("Faild", "Person is not available", "OK");
  20. }
  21. }
  22. }
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. private void BtnUpdate_Clicked(object sender, EventArgs e)
  7. {
  8. if (!string.IsNullOrEmpty(txtPersonId.Text))
  9. {
  10. Person person = new Person()
  11. {
  12. PersonId = Convert.ToInt32(txtPersonId.Text),
  13. Name = txtName.Text
  14. };
  15. //Update person
  16. App.LiteDB.UpdatePerson(person);
  17. txtName.Text = string.Empty;
  18. txtPersonId.Text = string.Empty;
  19. DisplayAlert("Success", "Person Updated", "OK");
  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
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. rivate void BtnDelete_Clicked(object sender, EventArgs e)
  7. {
  8. if(!string.IsNullOrEmpty(txtPersonId.Text))
  9. {
  10. //Delete Person
  11. App.LiteDB.DeletePerson(Convert.ToInt32(txtPersonId.Text));
  12. txtPersonId.Text = string.Empty;
  13. DisplayAlert("Warning", "Person Deleted!", "OK");
  14. //Get All Persons
  15. var personList = App.LiteDB.GetAllPersons();
  16. if (personList.Count != 0)
  17. {
  18. lstPersons.ItemsSource = personList;
  19. }
  20. }
  21. }
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. public LiteDBHelper(string dbPath)
  12. {
  13. using (var db = new LiteDatabase(dbPath))
  14. {
  15. personCollection = db.GetCollection<Person>("Persons");
  16. }
  17. }
  18. //Get All Persons
  19. public List<Person> GetAllPersons()
  20. {
  21. var persons= new List<Person>(personCollection.FindAll());
  22. return persons;
  23. }
  24. //Add New Person
  25. public void AddPerson(Person person)
  26. {
  27. personCollection.Insert(person);
  28. }
  29. //Update Person
  30. public void UpdatePerson(Person person)
  31. {
  32. personCollection.Update(person);
  33. }
  34. //Get Person
  35. public Person GetPerson(int personId)
  36. {
  37. var person = GetAllPersons().Where(a => a.PersonId == personId).FirstOrDefault();
  38. return person;
  39. }
  40. //Delete Person
  41. public void DeletePerson(int personId)
  42. {
  43. personCollection.Delete(a => a.PersonId == personId);
  44. }
  45. }
  46. }
MainPage.Xaml.cs
  1. using Xamarin.Forms;
  2. namespace XamarinLiteDB
  3. {
  4. public partial class MainPage : ContentPage
  5. {
  6. public MainPage()
  7. {
  8. InitializeComponent();
  9. //Get All Persons
  10. var personList=App.LiteDB.GetAllPersons();
  11. if(personList.Count!=0)
  12. {
  13. lstPersons.ItemsSource = personList;
  14. }
  15. }
  16. private void BtnAdd_Clicked(object sender, EventArgs e)
  17. {
  18. if (!string.IsNullOrEmpty(txtName.Text))
  19. {
  20. Person person = new Person()
  21. {
  22. Name = txtName.Text
  23. };
  24. //Add New Person
  25. App.LiteDB.AddPerson(person);
  26. txtName.Text = string.Empty;
  27. DisplayAlert("Success", "Person Added", "OK");
  28. //Get All Persons
  29. var personList = App.LiteDB.GetAllPersons();
  30. if (personList.Count != 0)
  31. {
  32. lstPersons.ItemsSource = personList;
  33. }
  34. }
  35. }
  36. private void BtnRead_Clicked(object sender, EventArgs e)
  37. {
  38. if(!string.IsNullOrEmpty(txtPersonId.Text))
  39. {
  40. var person= App.LiteDB.GetPerson(Convert.ToInt32(txtPersonId.Text));
  41. if(person!=null)
  42. {
  43. txtName.Text = person.Name;
  44. DisplayAlert("Success", "Person Name: "+person.Name, "OK");
  45. }
  46. else
  47. {
  48. DisplayAlert("Faild", "Person is not available", "OK");
  49. }
  50. }
  51. }
  52. private void BtnUpdate_Clicked(object sender, EventArgs e)
  53. {
  54. if (!string.IsNullOrEmpty(txtPersonId.Text))
  55. {
  56. Person person = new Person()
  57. {
  58. PersonId = Convert.ToInt32(txtPersonId.Text),
  59. Name = txtName.Text
  60. };
  61. //Update person
  62. App.LiteDB.UpdatePerson(person);
  63. txtName.Text = string.Empty;
  64. txtPersonId.Text = string.Empty;
  65. DisplayAlert("Success", "Person Updated", "OK");
  66. //Get All Persons
  67. var personList = App.LiteDB.GetAllPersons();
  68. if (personList.Count != 0)
  69. {
  70. lstPersons.ItemsSource = personList;
  71. }
  72. }
  73. }
  74. private void BtnDelete_Clicked(object sender, EventArgs e)
  75. {
  76. if(!string.IsNullOrEmpty(txtPersonId.Text))
  77. {
  78. //Delete Person
  79. App.LiteDB.DeletePerson(Convert.ToInt32(txtPersonId.Text));
  80. txtPersonId.Text = string.Empty;
  81. DisplayAlert("Warning", "Person Deleted!", "OK");
  82. //Get All Persons
  83. var personList = App.LiteDB.GetAllPersons();
  84. if (personList.Count != 0)
  85. {
  86. lstPersons.ItemsSource = personList;
  87. }
  88. }
  89. }
  90. }
  91. }
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 :)