How to use LiteDB in C#

By FoxLearn 1/7/2025 8:36:39 AM   96
LiteDB is a lightweight, fast, and easy-to-use embedded NoSQL database for .NET.

It is ideal for simple applications (web, mobile, or desktop) that require a single data file per user, but do not need to handle many simultaneous write operations. It is zero-configuration, making it straightforward to set up.

LiteDB uses two main concepts: documents and collections. Documents store and retrieve data in BSON format, and can be defined using either a POCO class or a BsonDocument class. These documents are organized within collections, which are identified by unique names and contain documents with the same schema.

The key methods for working with documents in a collection are:

  • Insert: Adds a new document.
  • Update: Modifies an existing document.
  • Delete: Removes a document.
  • FindById/Find: Queries documents.
  • Include: Populates properties from other collections.
  • EnsureIndex: Creates a new index if it doesn't exist.

LiteDB is a server-less database, meaning you don't need to install it on your system.

You can simply add a reference to the LiteDB.dll file in your project, or install it through the NuGet Package Manager in Visual Studio by running the command: Install-Package LiteDB.

Create a POCO Class in LiteDB in C#

Start by creating a new console application in Visual Studio and save it with a name.

For this example, let’s create a POCO (Plain Old C# Object) class that will represent a strongly typed document in LiteDB. Your class should have an Id property, which can either be named Id or marked with the [BsonId] attribute.

public class Book
{
    public int Id { get; set; }
    public string Title { get; set; }
    public string Author { get; set; }
}

The Id property should be unique and not null. If left empty, LiteDB will automatically generate an Id when inserting a new record.

Insert a Record in LiteDB in C#

To insert a new record, use the following code snippet. It creates a Book instance and inserts it into the database.

using (var db = new LiteDatabase(connectionString))
{
    var collection = db.GetCollection<Book>("books");
    var book = new Book
    {
        Title = "Learn C#",
        Author = "John Doe"
    };
    collection.Insert(book);
}

In this example, a new LiteDatabase instance is created with a connection string. The GetCollection<Book> method retrieves or creates the collection, and the Insert method automatically generates an Id and inserts the document.

Query LiteDB in C#

Once a record is inserted, you can query it using the following code:

using (var db = new LiteDatabase(connectionString))
{
    var collection = db.GetCollection<Book>("books");
    var book = collection.FindById(1);
    Console.WriteLine(book.Title + " by " + book.Author);
}

The FindById method retrieves the document by its Id. Additionally, you can create an index on a property like Title:

collection.EnsureIndex("Title");

Update data in LiteDB in C#

Updating data is simple: modify the property values and call the Update method on the collection:

var book = collection.FindById(1);
book.Author = "Jane Doe";
collection.Update(book);

To query all books by a specific author, use:

var results = collection.Find(x => x.Author.Contains("Jane Doe"));

LiteDB also offers a LiteRepository class to make CRUD operations easier:

using (var db = new LiteRepository(connectionString))
{
    db.Insert(new Book { Title = "Learn C#", Author = "John Doe" });
}

Working with Files in LiteDB

LiteDB provides a FileStorage collection to upload and download files.

For uploading a file:

db.FileStorage.Upload("BookCover", @"C:\Temp\BookCover.jpg");

To download the file:

db.FileStorage.Download("BookCover", @"C:\IDG\BookCover.jpg");

LiteDB manages file-related data with two collections: _files for metadata and _chunks for file data storage.