SoFunction
Updated on 2025-03-06

C# LiteDB basic usage example code

LiteDB is a small, fast and lightweight .NET NoSQL embedded database, which is what we often call K/V database. It is developed completely with C# hosted code, and is free and open source. The Github Star count is nearly 7k. It is ideal for use in mobile applications (Xamarin iOS/Android) and small desktop/Web applications.

LiteDB is inspired by MongoDB databases, so its API is very similar to MongoDB's .NET API.

LiteDB is a single-file database that accesses data based on Key-Value.

LiteDB's basic data structure

BsonDocument

BsonDocumentUsed to store a single object, its constructor receives typical data and defines the specific contents of the storage.

BsonArray

BsonArrayUsed to store multiple objects of the same type, and its constructor receives a collection of objects.

BsonValue

BsonValueyesBsonDocumentandBsonArrayThe public base class can determine its specific type at runtime, through a series ofAs*Method converts it to a concrete type.

Basic use of LiteDB

1. Create entity class

Create an entity class

{
    public int Id { get; set; }
    public int Age { get; set; }
    public string Name { get; set; } = ;
    public string[] Phone { get; set; }
    public bool IsActive { get; set; }
}

2. Connect to the database and some CRUDs

Add LiteDB in NuGet

    // Open the database and automatically create it if it does not exist.    var db = new LiteDatabase(@"");
    // Add, delete and modify cases    // Get Student collection object    var col = <Student>("student");
    for(int i = 1; i < 10; i++) 
    {
        var student = new Student()
        {
            Id = i,
            Age = 18+i,
            Name = "Test",
            Phone = new string[] { "8000-1000"+i, "1001-8080"+i },
            IsActive = true, 
         };
        // Data insertion        (student);
    }
    // Create a unique index on the id field    (x => , true);
    // Data query    List<Student> list = (x =>  > 20).ToList();
    Student user = (x =>  == 1);
    ($"LiteThere are{}People are older than20The person");
    foreach (Student stu in list)
    {
        ShowInfo(stu);
    }
    ("People with Id of 1 in the Lite database");
    ShowInfo(user);
	// Delete all data    ();
}
static void ShowInfo(Student student)
{
    ("Name:"+ + "age:"+);
}

This is the article about the basic usage example code of C# LiteDB. For more information about usage of C# LiteDB, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!