dcsimg

WEBINAR:
On-Demand

Virtual Developer Workshop: Containerized Development with Docker


Introduction

LiteDB is a simple, serverless, fast and lightweight, embedded .NET document database written in .NET C# managed code. It's completely open source and free to use, even for commercial use. It's compatible with .NET 3.5, 4.x, and NET Standard 1.3 and 2.0. LiteDB was developed by Mauricio David; he was inspired by the MongoDB database and its APIs. LiteDB supports Document ACID transaction, storing files and stream data, and provides LINQ support. A developer simply can add a reference of the LiteDB.dll file in the project. Also, LiteDB can be installed via the NuGet Package Manager in Visual Studio or by typing the following command in the NuGet Package Manager command line tool:.

Install-Package LiteDB

LiteDB Documentation

LiteDB maintains online documentation. For developers, I would suggest going to "Getting Started." LiteDB works with documents and collections. Documents are used to store and retrieve data to and from a data file. Here is a list of operations supported by LiteDB:

  • Insert: Used to add a new document to the collection
  • Update: Used to update an existing document saved earlier
  • Delete: Used to delete an existing document saved earlier
  • FindById or Find: Used to write a query to fetch a document saved earlier
  • EnsureIndex: Used to create a new index if it doesn't exist already

Coding a .NET Sample Application

To demonstrate LiteDB functionalities, I have created a new .NET console application project in Visual Studio and saved it with the name LiteDBSample (see Figure 1).

New LiteDB console application
Figure 1: New LiteDB console application

Next, from the NuGet package manager, I have installed LiteDB. Refer to Figure 2.

Add LiteDB NuGet package in the console application
Figure 2: Add LiteDB NuGet package in the console application

After installing the LiteDB NuGet package, I have added an Employee class that we will use it to create a strongly typed document. The EmployeeId property should be unique, not null, and of the Employee class.

Now, refer to the following C# code snippet to create a new Employee instance and insert a record, update an existing employee, find an employee, create an index, and finally, delete an employee from the collection.

using LiteDB;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace LiteDBSample
{
   public class Employee
   {
      public int EmployeeId { get; set; }
      public string EmployeeName { get; set; }
      public string CompanyName { get; set; }
      public string Department { get; set; }
      public string Skill { get; set; }
      public string PhoneNumber { get; set; }
      public string Address { get; set; }
   }
   class Program
   {

      static void Main(string[] args)
      {

         try
         {
            using (var db = new LiteDatabase(@"C:\\Tapas\\
               MyLiteData.db"))
            {
               var Employees = db.GetCollection<Employee>
                  ("Employee");
               var Employee = new Employee
               {
                  EmployeeId = 12345,
                  EmployeeName = "Tapas Pal",
                  CompanyName = "TCS",
                  Department = "IT",
                  Skill = ".NET,C#,SQL,HTML",
                  PhoneNumber = "1234567890",
                  Address = "Kolkata,India"
               };
               // Insert record
               Employees.Insert(Employee);
               // Update record
               Employee.EmployeeName = "New Employee";
               Employees.Update(Employee);
               // Find record
               var collection = db.GetCollection<Employee>
                  ("Employee");
               var EmployeeFine = collection.FindById(1);
               Console.WriteLine(EmployeeFine.EmployeeName + " "
                  +EmployeeFine.EmployeeId);
               // Create Index
               Employees.EnsureIndex("EmployeeId");
               Employees.Delete(1);

            }
         }
         catch (Exception ex)
         {

         }
      }

   }
}

To demonstrate query functionality, I have inserted one more employee record. You can query it as shown in the following code snippet. The Find method returns the document/documents by its Id or the primary key index. You can explicitly create an index by using the EnsureIndex method, as mentioned in the preceding code snippet.

               // Create one more employee
               var Employee1 = new Employee
               {
                  EmployeeId = 12346,
                  EmployeeName = "XYZ ZYZ",
                  CompanyName = "TCS",
                  Department = "IT",
                  Skill = ".NET,C#,SQL,HTML",
                  PhoneNumber = "1234567899",
                  Address = "Kolkata,India"
               };
               // Insert record
               Employees.Insert(Employee1);
               var collection1 = db.GetCollection<Employee>
                  ("Employee");
               var results = collection.Find(x =>
                  x.Address.Contains("Kolkata"));

Refer to the following code snippet that demonstrate file storage functionality that is similar to the MongoDB API.

   try
   {
      using (var db = new LiteDatabase(@"C:\\Tapas\\
         MyLiteData.db"))
      {
         // Upload a file from file system
         db.FileStorage.Upload("$/Tapas/photos/mypicture-01.jpg",
            @"C:\Local\mypicture-01.jpg");

         // Upload a file from a Stream
         db.FileStorage.Upload("$/Tapas/photos/mypicture-01.jpg",
            "mypicture-01.jpg", stream);

        // Find file reference only
        LiteFileInfo file = db.FileStorage.FindById
           ("$/Tapas/photos/mypicture-01.jpg");

        // Now, load binary data and save to file system
        file.SaveAs(@"C:\Tapas\mynew-picture.jpg");

        // Or get binary data as Stream and copy to another Stream
        file.CopyTo(Response.OutputStream);

        // Find all files references in a "directory"
        var files = db.FileStorage.Find("$/Tapas/photos/");

      }

   }
   catch (Exception ex)
   {

   }

Conclusion

I hope this article gave you a basic, high-level understanding on LiteDB and how to use it. Remember, while inserting a document in LiteDB, the document structure is required because each document must contain an unique Id value field. If you do not provide this, LiteDB will auto create this Id field by using ObjectId.

That's all for today. Happy coding!



About the Author

Tapas Pal

I am working in Microsoft Technology for last 15 years and presently working with Cognizant Technology Solutions, India as Senior Architect. I have completed TOGAF 9.1,Microsoft Certification on .NET 1.1 , .NET 2.0, SQL Server 2005 and Sharepoint. Please visit my Blog - http://tapas-pal.blogspot.com/

Related Articles

Comments

  • There are no comments yet. Be the first to comment!

  • You must have javascript enabled in order to post comments.

Leave a Comment
  • Your email address will not be published. All fields are required.

Most Popular Programming Stories

More for Developers

RSS Feeds

Thanks for your registration, follow us on our social networks to keep up-to-date