How to work with LiteDB in C#

Take advantage of the fast, lightweight, and easy-to-use LiteDB for your desktop, mobile, and simple web applications

How to work with LiteDB in C#
Thinkstock

LiteDB is a fast, simple, zero-configuration, embedded NoSQL database for .Net. It is a good choice for simple applications (web, mobile, or desktop) where you may need one data file per user but don’t need to support many concurrent write operations. This article presents an overview on how we can work with this database using C#.

Before we start using LiteDB, let’s take a look at some of the concepts. LiteDB works with documents and collections. Documents are used to store and retrieve data to and from a data file. Note that your document definition can either be a POCO class or a BsonDocument class. Either way, LiteDB will convert your document to BSON format before it is stored in the database.

LiteDB organizes the documents inside document stores known as collections. Incidentally, each collection is identified by a unique name and contains one or more documents that share the same schema. To work with documents, you can take advantage of the methods of the collection. Here is the list of the methods you can use:

  • Insert—used to add a new document to the collection
  • Update—used to update an existing document
  • Delete—used to delete a document
  • FindById or Find—used to query a document
  • Include—used to populate properties from other collections
  • EnsureIndex—used to create a new index if it doesn’t exist

Because LiteDB is a server-less database, you don’t need to install it in your system. You simply add a reference to the LiteDB.dll file in your project. Alternatively, you can install LiteDB 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

Create a POCO class in LiteDB in C#

Create a new console application project in Visual Studio and save it with a name. Let’s now create a POCO class that we will use it to create a strongly typed document. Note that we should have an Id named property in our class to work with LiteDB. Alternatively, we can also decorate any property in our class with the [BsonId] attribute. Here’s the Author class we would use in this example.

public class Author
    {
        public int Id { get; set; }
        public string FirstName { get; set; }
        public string LastName { get; set; }
    }

The Id property should be unique and not null. If you leave the Id property empty, LiteDB will automatically generate the Id when inserting a record.

Insert a record in LiteDB in C#

The following code snippet can be used to create a new Author instance and insert a record.

using (var db = new LiteDatabase(connectionString))
    {
       var collection = db.GetCollection<Author>(“authors”);
       var author = new Author
         {
             FirstName ="Joydip",
             LastName ="Kanjilal",
             Address ="Hyderabad"
          };
         collection.Insert(author);
     }

Refer to the code snippet above. Note how a new instance of LiteDatabase is created by passing the connection string as a parameter. The following statement retrieves a collection or creates a new collection if none exists. The call to the Insert method on the collection instance automatically generates the value of the Id property and inserts the document into the database.

Query LiteDB in C#

Now that you have inserted a new record in the database, you can query it as shown in the code snippet below.

using (var db = new LiteDatabase(connectionString))
   {
     var collection = db.GetCollection<Author>(“authors”);
     var author = collection.FindById(1);
     Console.WriteLine(author.FirstName + “\t” +author.LastName);
   }

Note that the FindById method returns the document by its Id or the primary key index. You can explicitly create an index using the EnsureIndex method as shown below.

authors.EnsureIndex(“FirstName”);

Update a document in LiteDB in C#

Updating a document is simple. You simply change the property values and then call the Update method on the collection instance as shown below.

var author = collection.FindById(1);
author.Address ="Kolkata";
collection.Update(author);

If you would like to find all authors who live in a particular location, you can use the following query.

var results = collection.Find(x => x.Address.Contains(“Hyderabad”));

There is another class called LiteRepository that makes it a bit easier to perform CRUD operations. Here is an example that illustrates how you can use this class.

using (var db = new LiteRepository(connectionString))
            {
                db.Insert (new Author
               { FirstName ="Joydip", LastName ="Kanjilal",
               Address ="Hyderabad" });
            }

Working with files in LiteDB

LiteDB provides the FileStorage collection for working with files. Uploading or downloading files is simple. All you need to do is call the appropriate method on the FileStorage collection as shown in the code snippets below. To upload a file:

db.FileStorage.Upload(“Author-Photo”, @”C:\Temp\Joydip.jpg”); //Uploads a file to the database
To download a file:
db.FileStorage.Download(“Author-Photo”, @”C:\IDG\Joydip.jpg”); //Downloads a file to the file system

It should be noted that LiteDB creates two collections to work with files. These include _files and _chunks. The ­_files collection contains information related to the file’s metadata, and _chunks contains data that is split appropriately for storage.