푸터 콘텐츠로 바로가기
.NET 도움말

LiteDB .NET (How It Works For Developers)

LiteDB is a simple, fast, and lightweight embedded .NET document database. LiteDB .NET was inspired by the MongoDB database and its API is very similar to MongoDB’s official .NET API. LiteDB is a serverless database that works well for small projects and mobile applications.

This article will provide you with accurate instructions on utilizing the capabilities of LiteDB in your projects. We also introduce the use of IronPDF, a .NET library made by Iron Software, for generating and manipulating PDFs and how you can employ it to output a LiteDB database contents as a PDF for viewing and sharing.

Key Features of LiteDB

  1. Embedded Database: No need for a separate server. LiteDB runs within your application's process.
  2. Single Data File: You can store in a single file database, all of your data, simplifying deployment and backup.
  3. BSON Format: Uses BSON format for storage, ensuring fast read and write operations.
  4. LINQ Support: Fully supports LINQ for querying, making it intuitive for .NET developers.
  5. ACID Transactions: Ensures data integrity with support for ACID transactions.
  6. Cross-Platform: Works on Windows, Linux, and macOS.

Setting Up LiteDB in .NET Projects

Open your project in Visual Studio. Then, in the Solution Explorer, right-click on your project and choose "Manage NuGet Packages." Search for LiteDB and install it to incorporate this database solution into your project effortlessly.

Alternatively, you can install it by using Package Manager Console. To install LiteDB in the NuGet Package Manager Console, use the following command:

Install-Package LiteDB

Getting Started with LiteDB

Once installed, you can start using LiteDB in your application. Let's go through some examples to illustrate its usage.

Example 1: Creating and Inserting Data

First, let's create a simple Product class to represent our data:

public class Product
{
    public int Id { get; set; }
    public string Name { get; set; }
    public decimal Price { get; set; }
}
public class Product
{
    public int Id { get; set; }
    public string Name { get; set; }
    public decimal Price { get; set; }
}
$vbLabelText   $csharpLabel

Next, we'll create a database and insert some products:

using LiteDB;
using System;

class Program
{
    static void Main()
    {
        // Open the database (or create it if it doesn't exist)
        using (var db = new LiteDatabase(@"MyData.db"))
        {
            // Get a collection (or create, if it doesn't exist)
            var products = db.GetCollection<Product>("products");

            // Create a list of products to insert into the database
            var productList = new[]
            {
                new Product { Id = 201, Name = "Apple", Price = 0.99m },
                new Product { Id = 202, Name = "Banana", Price = 0.59m },
                new Product { Id = 203, Name = "Orange", Price = 0.79m },
                new Product { Id = 204, Name = "Grape", Price = 2.99m },
                new Product { Id = 205, Name = "Watermelon", Price = 4.99m }
            };

            // Insert each product into the collection
            foreach (var product in productList)
            {
                products.Insert(product);
            }

            Console.WriteLine("Product inserted successfully.");
        }
    }
}
using LiteDB;
using System;

class Program
{
    static void Main()
    {
        // Open the database (or create it if it doesn't exist)
        using (var db = new LiteDatabase(@"MyData.db"))
        {
            // Get a collection (or create, if it doesn't exist)
            var products = db.GetCollection<Product>("products");

            // Create a list of products to insert into the database
            var productList = new[]
            {
                new Product { Id = 201, Name = "Apple", Price = 0.99m },
                new Product { Id = 202, Name = "Banana", Price = 0.59m },
                new Product { Id = 203, Name = "Orange", Price = 0.79m },
                new Product { Id = 204, Name = "Grape", Price = 2.99m },
                new Product { Id = 205, Name = "Watermelon", Price = 4.99m }
            };

            // Insert each product into the collection
            foreach (var product in productList)
            {
                products.Insert(product);
            }

            Console.WriteLine("Product inserted successfully.");
        }
    }
}
$vbLabelText   $csharpLabel

Code Description

The code initializes a connection to a LiteDB database named "MyData.db" and retrieves a collection called "products." It then creates an array of Product objects with various properties, such as ID, Name, and Price. Each product in the array is inserted into the "products" collection within the database. After successfully inserting all products, it prints a confirmation message to the console.

Output is as:

LiteDB .NET (How It Works For Developers): Figure 1 - Console output from the previous code

Example: Streamlining User Data Management

Imagine you're developing a mobile application that manages user accounts. Each user has a profile containing their name, email address, preferences (stored as a JSON object), and a list of favorite items. Here's how LiteDb.NET can simplify your data storage:

This code defines a User class to represent user data and a UserManager class to manage user operations in a LiteDb.NET database

using LiteDB;
using System.Collections.Generic;

public class User
{
    [BsonId]
    public string Id { get; set; }
    public string Name { get; set; }
    public string Email { get; set; }
    public Dictionary<string, string> Preferences { get; set; }
    public List<string> FavoriteItems { get; set; }
} 

public class UserManager
{
    private readonly LiteDatabase db;

    public UserManager(string connectionString)
    {
       db = new LiteDatabase(connectionString);
    }

    public void SaveUser(User user)
    {
        var collection = db.GetCollection<User>("users");
        collection.Insert(user);
    }

    public User GetUser(string userId)
    {
        var collection = db.GetCollection<User>("users");
        return collection.FindById(userId);
    }

    public void UpdateUser(User user)
    {
        var collection = db.GetCollection<User>("users");
        collection.Update(user);
    }

    public void DeleteUser(string userId)
    {
        var collection = db.GetCollection<User>("users");
        collection.Delete(userId);
    }
}
using LiteDB;
using System.Collections.Generic;

public class User
{
    [BsonId]
    public string Id { get; set; }
    public string Name { get; set; }
    public string Email { get; set; }
    public Dictionary<string, string> Preferences { get; set; }
    public List<string> FavoriteItems { get; set; }
} 

public class UserManager
{
    private readonly LiteDatabase db;

    public UserManager(string connectionString)
    {
       db = new LiteDatabase(connectionString);
    }

    public void SaveUser(User user)
    {
        var collection = db.GetCollection<User>("users");
        collection.Insert(user);
    }

    public User GetUser(string userId)
    {
        var collection = db.GetCollection<User>("users");
        return collection.FindById(userId);
    }

    public void UpdateUser(User user)
    {
        var collection = db.GetCollection<User>("users");
        collection.Update(user);
    }

    public void DeleteUser(string userId)
    {
        var collection = db.GetCollection<User>("users");
        collection.Delete(userId);
    }
}
$vbLabelText   $csharpLabel

This implementation effectively leverages LiteDb.NET's capabilities for user data management. The User class stores user information, while the UserManager class provides methods to save, retrieve, update, and delete users within the database.

LiteDB, embedded NoSQL database for .NET

LiteDB is perfect for small to medium-sized applications without user concurrency needs. For instance, it's great for a personal console app where you want to store data simply and swiftly. Developed solely in C#, it's lightweight, takes up less than 450KB, and doesn't rely on external dependencies.

Some more points, which are listed on their GitHub page:

  1. Serverless NoSQL Document Store
  2. Simple API, similar to MongoDB
  3. Thread-safe
  4. Written entirely in C#, LiteDB is compatible with .NET 4.5, NETStandard 1.3/2.0, packaged into a single DLL file that occupies less than 450KB.
  5. ACID with full transaction support
  6. Data recovery after write failure (WAL log file)
  7. Datafile encryption using AES cryptography
  8. You can easily map your Plain Old CLR Objects (POCO) classes to BsonDocument using either attributes or the fluent mapper API provided by LiteDB.
  9. Store files and stream data (like GridFS in MongoDB)
  10. Single data file storage (like SQLite)
  11. Index document fields for fast search
  12. LINQ support for queries
  13. SQL-Like commands to access/transform data
  14. LiteDB Studio – Nice UI for data access
  15. Open source and free for everyone – including commercial use

Introduction to IronPDF: A C# PDF Library

LiteDB .NET (How It Works For Developers): Figure 2 - IronPDF webpage

IronPDF, a premier C# PDF library, facilitates seamless creation, editing, and manipulation of PDFs in .NET projects. It offers a comprehensive API for tasks like HTML to PDF conversion, dynamic PDF generation, and data extraction. Utilizing a .NET Chromium engine ensures accurate rendering of HTML into PDF files, catering to diverse project needs across .NET Core, .NET Standard, and .NET Framework. IronPDF guarantees precision, simplicity, and efficiency in PDF generation from HTML content with support for web, desktop, and console applications.

Installing IronPDF Library

To initiate IronPDF in your project, install the library via the NuGet Package Manager within Visual Studio. Then simply follow these straightforward steps:

  1. Open Visual Studio and navigate to Solution Explorer.
  2. Right-click on Dependencies and select the "Manage NuGet Packages" option.
  3. Choose the "Browse" tab and search for "IronPdf."
  4. Select IronPDF and click "Install."

Alternatively, within Visual Studio, you can utilize the Package Manager Console to install the library by executing the following command:

Install-Package IronPdf

Example Usage of IronPDF with LiteDB

Here's a straightforward code example illustrating the usage of IronPDF to generate a PDF from HTML content, employing the 'using' statement to ensure proper resource disposal. Here we combine the functionality of LiteDB and IronPDF by showing how you can output the data within a LiteDB as a PDF for viewing purposes:

using LiteDB;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using IronPdf;

class Program
{
    static void Main()
    {
        using (var db = new LiteDatabase(@"MyData.db"))
        {
            // Retrieve the 'products' collection or create it
            var products = db.GetCollection<Product>("products");

            // Add some initial products to the collection
            var productList = new[]
            {
                new Product { Id = 101, Name = "Apple", Price = 0.99m },
                new Product { Id = 102, Name = "Banana", Price = 0.59m },
                new Product { Id = 103, Name = "Orange", Price = 0.79m },
                new Product { Id = 104, Name = "Grape", Price = 2.99m },
                new Product { Id = 105, Name = "Watermelon", Price = 4.99m }
            };

            // Insert products into the LiteDB collection
            foreach (var product in productList)
            {
                products.Insert(product);
            }

            Console.WriteLine("Product inserted successfully.");

            // Fetch all products from the database
            var allProducts = GetAllProducts(db);

            // Generate HTML content from the product list
            string htmlContent = GenerateHtml(allProducts);

            // Generate the PDF from the HTML content
            GeneratePDF(htmlContent);

            Console.WriteLine("PDF generated successfully.");
        }
    }

    public static List<Product> GetAllProducts(LiteDatabase db)
    {
        var products = db.GetCollection<Product>("products");
        return products.FindAll().ToList();
    }

    public static void GeneratePDF(string data)
    {
        // Set your IronPDF license key here
        IronPdf.License.LicenseKey = "Your-License-Key";
        Console.WriteLine("PDF Generating Started...");

        // Create a PDF renderer
        var renderer = new ChromePdfRenderer();
        Console.WriteLine("PDF Processing ....");

        // Render the HTML as a PDF
        var pdf = renderer.RenderHtmlAsPdf(data);

        // Save the PDF to a file
        string filePath = "Data.pdf";
        pdf.SaveAs(filePath);

        Console.WriteLine($"PDF Generation Completed, File Saved as {filePath}");
    }

    public static string GenerateHtml(List<Product> products)
    {
        // Build HTML table from product list
        StringBuilder htmlBuilder = new StringBuilder();
        htmlBuilder.Append("<html><head><style>table { width: 100%; border-collapse: collapse; } th, td { border: 1px solid black; padding: 8px; text-align: left; }</style></head><body>");
        htmlBuilder.Append("<h1>Product List</h1>");
        htmlBuilder.Append("<table><tr><th>ID</th><th>Name</th><th>Price</th></tr>");

        // Add each product row to the HTML table
        foreach (var product in products)
        {
            htmlBuilder.Append($"<tr><td>{product.Id}</td><td>{product.Name}</td><td>{product.Price:C}</td></tr>");
        }

        htmlBuilder.Append("</table></body></html>");
        return htmlBuilder.ToString();
    }
}
using LiteDB;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using IronPdf;

class Program
{
    static void Main()
    {
        using (var db = new LiteDatabase(@"MyData.db"))
        {
            // Retrieve the 'products' collection or create it
            var products = db.GetCollection<Product>("products");

            // Add some initial products to the collection
            var productList = new[]
            {
                new Product { Id = 101, Name = "Apple", Price = 0.99m },
                new Product { Id = 102, Name = "Banana", Price = 0.59m },
                new Product { Id = 103, Name = "Orange", Price = 0.79m },
                new Product { Id = 104, Name = "Grape", Price = 2.99m },
                new Product { Id = 105, Name = "Watermelon", Price = 4.99m }
            };

            // Insert products into the LiteDB collection
            foreach (var product in productList)
            {
                products.Insert(product);
            }

            Console.WriteLine("Product inserted successfully.");

            // Fetch all products from the database
            var allProducts = GetAllProducts(db);

            // Generate HTML content from the product list
            string htmlContent = GenerateHtml(allProducts);

            // Generate the PDF from the HTML content
            GeneratePDF(htmlContent);

            Console.WriteLine("PDF generated successfully.");
        }
    }

    public static List<Product> GetAllProducts(LiteDatabase db)
    {
        var products = db.GetCollection<Product>("products");
        return products.FindAll().ToList();
    }

    public static void GeneratePDF(string data)
    {
        // Set your IronPDF license key here
        IronPdf.License.LicenseKey = "Your-License-Key";
        Console.WriteLine("PDF Generating Started...");

        // Create a PDF renderer
        var renderer = new ChromePdfRenderer();
        Console.WriteLine("PDF Processing ....");

        // Render the HTML as a PDF
        var pdf = renderer.RenderHtmlAsPdf(data);

        // Save the PDF to a file
        string filePath = "Data.pdf";
        pdf.SaveAs(filePath);

        Console.WriteLine($"PDF Generation Completed, File Saved as {filePath}");
    }

    public static string GenerateHtml(List<Product> products)
    {
        // Build HTML table from product list
        StringBuilder htmlBuilder = new StringBuilder();
        htmlBuilder.Append("<html><head><style>table { width: 100%; border-collapse: collapse; } th, td { border: 1px solid black; padding: 8px; text-align: left; }</style></head><body>");
        htmlBuilder.Append("<h1>Product List</h1>");
        htmlBuilder.Append("<table><tr><th>ID</th><th>Name</th><th>Price</th></tr>");

        // Add each product row to the HTML table
        foreach (var product in products)
        {
            htmlBuilder.Append($"<tr><td>{product.Id}</td><td>{product.Name}</td><td>{product.Price:C}</td></tr>");
        }

        htmlBuilder.Append("</table></body></html>");
        return htmlBuilder.ToString();
    }
}
$vbLabelText   $csharpLabel

The code connects to a LiteDB database, adds a list of products, retrieves all products, and generates an HTML representation of the product list. This HTML content is then used to create a PDF file using the IronPDF library. The process includes methods for adding products, fetching them, converting the product list to HTML, and generating the PDF.

Output

LiteDB .NET (How It Works For Developers): Figure 3 - Console output from the previous code

PDF File Output

LiteDB .NET (How It Works For Developers): Figure 4 - Outputted PDF from the previous code

Conclusion

LiteDB presents C# developers with a lightweight, serverless embedded document database solution, ideal for small projects and mobile applications, boasting features like MongoDB-inspired API, embedded databases, and cross-platform compatibility.

Simultaneously, IronPDF emerges as a premier C# PDF library, simplifying PDF generation and manipulation within .NET projects with its HTML to PDF conversion and NuGet integration. Both LiteDB and IronPDF offer valuable tools for developers, with LiteDB excelling in database management and IronPDF in PDF handling.

IronPDF provides a free trial to unlock its full potential in PDF generation and manipulation.

자주 묻는 질문

C#에서 HTML 콘텐츠를 PDF로 변환하려면 어떻게 해야 하나요?

IronPDF를 사용하여 C#에서 HTML 콘텐츠를 PDF로 변환할 수 있습니다. 이 라이브러리는 HTML 문자열을 PDF 문서로 변환할 수 있는 RenderHtmlAsPdf와 같은 메서드를 제공합니다.

LiteDB를 .NET 프로젝트와 통합하는 가장 좋은 방법은 무엇인가요?

LiteDB를 .NET 프로젝트와 통합하려면 Visual Studio의 NuGet 패키지 관리자를 사용하여 LiteDB를 설치할 수 있습니다. 그러면 C#을 사용하여 애플리케이션 내에서 직접 데이터베이스를 관리할 수 있습니다.

LiteDB 데이터에서 PDF를 생성하려면 어떻게 해야 하나요?

LiteDB 데이터에서 PDF를 생성하려면 IronPDF를 사용할 수 있습니다. LiteDB에서 데이터를 추출하고 IronPDF의 기능을 사용하여 렌더링하면 보고 또는 공유 목적으로 PDF 문서를 만들 수 있습니다.

IronPDF를 사용하여 C#에서 기존 PDF 파일을 조작할 수 있나요?

예, IronPDF는 기존 PDF 파일을 조작하는 데 사용할 수 있습니다. C# 애플리케이션 내에서 PDF의 콘텐츠를 편집, 병합 및 추출하는 기능을 제공합니다.

모바일 애플리케이션에 LiteDB를 사용할 수 있나요?

예, LiteDB는 가볍고 서버가 필요 없으며 단일 파일에 데이터를 저장할 수 있다는 특성으로 인해 모바일 애플리케이션에 특히 적합합니다.

LiteDB 통합에 대한 일반적인 문제 해결 단계는 무엇인가요?

LiteDB 통합을 위한 일반적인 문제 해결 단계에는 NuGet을 통해 올바르게 설치되었는지 확인하고, 데이터베이스 파일 경로에 액세스할 수 있는지 확인하고, 프로젝트의 .NET 버전이 LiteDB와 호환되는지 확인하는 것이 포함됩니다.

LiteDB를 사용하여 데이터 무결성을 보장하려면 어떻게 해야 하나요?

LiteDB는 데이터 무결성과 안정성을 보장하는 ACID 트랜잭션을 지원합니다. 트랜잭션을 사용하여 일관성을 유지하고 동시 데이터 수정을 처리할 수 있습니다.

.NET에서 PDF 생성에 IronPDF를 사용하면 어떤 이점이 있나요?

IronPDF는 간편한 HTML에서 PDF로의 변환, 높은 정확도의 렌더링, 포괄적인 PDF 조작 기능 등의 이점을 제공하므로 .NET 애플리케이션에서 PDF를 생성하고 처리하는 데 이상적입니다.

커티스 차우
기술 문서 작성자

커티스 차우는 칼턴 대학교에서 컴퓨터 과학 학사 학위를 취득했으며, Node.js, TypeScript, JavaScript, React를 전문으로 하는 프론트엔드 개발자입니다. 직관적이고 미적으로 뛰어난 사용자 인터페이스를 만드는 데 열정을 가진 그는 최신 프레임워크를 활용하고, 잘 구성되고 시각적으로 매력적인 매뉴얼을 제작하는 것을 즐깁니다.

커티스는 개발 분야 외에도 사물 인터넷(IoT)에 깊은 관심을 가지고 있으며, 하드웨어와 소프트웨어를 통합하는 혁신적인 방법을 연구합니다. 여가 시간에는 게임을 즐기거나 디스코드 봇을 만들면서 기술에 대한 애정과 창의성을 결합합니다.