.NET 幫助

LiteDB .NET(它如何為開發人員工作)

Chipego
奇佩戈·卡林达
2024年8月13日
分享:

介紹

LiteDB 是一個簡單、快速且輕量級的嵌入式 .NET 文件資料庫。 LiteDB .NET 的靈感來自 MongoDB 資料庫,其 API 與 MongoDB 的官方 .NET API 非常相似。 LiteDB 是一個無伺服器資料庫,適合小型專案和行動應用程式。

本文將為您提供如何在專案中利用LiteDB功能的準確指導。 我們亦介紹了使用由 Iron Software 開發的 .NET 程式庫 IronPDF 來生成和操作 PDF,及如何利用它將 LiteDB 資料庫內容輸出為 PDF,以便觀看和分享。

LiteDB 的主要特點

  1. 嵌入式資料庫:不需要單獨的伺服器。 LiteDB 在您的應用程式過程中運行。

  2. 单一数据文件:您可以將所有數據存儲在單一文件資料庫中,簡化部署和備份。

  3. BSON 格式:使用 BSON 格式進行存儲,確保快速讀取和寫入操作。

  4. LINQ 支援:完全支援 LINQ 進行查詢,這對 .NET 開發者來說非常直觀。

  5. ACID 交易:提供支援 ACID 交易以確保資料完整性。

  6. 跨平台:適用於Windows、Linux和macOS。

在 .NET 專案中設置 LiteDB

在 Visual Studio 中打開您的專案。 然後,在「解決方案總管」中,右鍵單擊您的專案並選擇「管理 NuGet 封裝」。搜尋 LiteDB 並安裝它,以便輕鬆地將這個資料庫解決方案整合到您的專案中。

或者,您可以使用套件管理器主控台來安裝它。 要在 NuGet 套件管理器控制台中安裝 LiteDB,請使用以下指令:

Install-Package LiteDB
Install-Package LiteDB
IRON VB CONVERTER ERROR developers@ironsoftware.com
$vbLabelText   $csharpLabel

開始使用LiteDB

安裝後,您可以在應用程式中開始使用LiteDB。 讓我們通過一些例子來說明它的用法。

範例 1:創建和插入數據

首先,我們來建立一個簡單的 Product 類別來表示我們的數據:

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; }
}
IRON VB CONVERTER ERROR developers@ironsoftware.com
$vbLabelText   $csharpLabel

接下來,我們將創建一個資料庫並插入一些產品:

using LiteDB;
using System;
class Program
{
   static void Main()
{
    using (var db = new LiteDatabase(@"MyData.db"))
    {
        var products = db.GetCollection<Product>("products");
        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 }
        };
        foreach (var product in productList)
        {
            products.Insert(product);
        }
        Console.WriteLine("Product inserted successfully.");
    }
}
}
using LiteDB;
using System;
class Program
{
   static void Main()
{
    using (var db = new LiteDatabase(@"MyData.db"))
    {
        var products = db.GetCollection<Product>("products");
        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 }
        };
        foreach (var product in productList)
        {
            products.Insert(product);
        }
        Console.WriteLine("Product inserted successfully.");
    }
}
}
IRON VB CONVERTER ERROR developers@ironsoftware.com
$vbLabelText   $csharpLabel

程式碼說明

這段程式碼初始化了與名為 "MyData.db" 的 LiteDB 資料庫的連接,並且檢索了一個名為 "products" 的集合。 接著,它建立一個包含各種屬性的 Product 物件陣列,例如 ID、名稱和價格。陣列中的每個產品都被插入到資料庫內的 "products" 集合中。 成功插入所有產品後,會在主控台打印確認訊息。

輸出為:

LiteDB .NET(開發人員指南):圖 1 - 來自先前代碼的控制台輸出

範例:精簡使用者資料管理

想像一下,您正在開發一個管理用戶帳戶的手機應用程式。 每位使用者都有一個包含姓名、電子郵件地址、偏好設定(存儲為 JSON 物件)和喜愛項目列表的個人檔案。 以下是 LiteDb.NET 如何簡化您的資料儲存方式:

此代碼定義了一個 User 類來表示用戶數據,以及一個 UserManager 類來管理 LiteDb.NET 数据庫中的用戶操作。

using LiteDB;
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;
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);
    }
}
IRON VB CONVERTER ERROR developers@ironsoftware.com
$vbLabelText   $csharpLabel

此實作有效地利用 LiteDb.NET 的功能來管理用戶數據。 User 類別用於儲存使用者資訊,而 UserManager 類別提供在資料庫中儲存、檢索、更新和刪除使用者的方法。

LiteDB,內嵌式 NoSQL 數據庫適用於 .NET

LiteDB 非常適合不需要使用者並發功能的小型至中型應用程式。 例如,這非常適合個人控制台應用程式,當你想要簡單快速地儲存資料時。 完全用 C# 開發,它輕量化,佔用不足 450KB,不依賴外部依賴項。

他們的GitHub 頁面上列出的一些更多要點:

  1. 無伺服器 NoSQL 文件存儲

  2. 簡單的 API,類似於 MongoDB

  3. 執行緒安全

  4. 全部以 C# 編寫的 LiteDB 與 .NET 4.5、NETStandard 1.3/2.0 兼容,打包成單一的 DLL 文件,佔用空間不足 450KB。

  5. 具有完整交易支持的ACID

  6. 寫入失敗後的資料復原(WAL 日誌檔)

  7. 使用 DES(AES)加密技術的數據文件加密

  8. 您可以使用屬性或由 LiteDB 提供的流暢映射器 API,輕鬆地將您的普通 CLR 物件 (POCO) 類別映射到 BsonDocument。

  9. 儲存檔案和串流數據(如 MongoDB 中的 GridFS)

    1. 單一數據文件存儲(如 SQLite)
  10. 索引文檔欄位以加快搜索速度

    1. 支援 LINQ 查詢
  11. 類似 SQL 的命令來訪問/轉換數據

    1. LiteDB Studio – 美觀的數據訪問界面
  12. 開源且免費供所有人使用——包括商業用途

IronPDF 介紹:一個 C# PDF 庫

LiteDB .NET(它如何為開發人員工作):圖 2 - IronPDF 網頁

IronPDF,一個卓越的 C# PDF 函式庫,方便在 .NET 專案中無縫創建編輯操作PDF 檔案。 它提供了一個全面的 API,用於完成如HTML 轉 PDF轉換、動態 PDF 生成和數據提取等任務。 利用 .NET Chromium 引擎,確保將 HTML 準確渲染為 PDF 文件,以滿足 .NET Core、.NET Standard 和 .NET Framework 的各種項目需求。 IronPDF 保證在從 HTML 內容生成 PDF 時提供精確、簡單和高效的體驗,並支援網頁、桌面和控制台應用程式。

安裝 IronPDF 函式庫

要在您的專案中啟動IronPDF,請透過Visual Studio中的NuGet Package Manager安裝該庫。 然後只需按照以下簡單步驟:

  1. 打開 Visual Studio 並導航至方案瀏覽器。

  2. 右鍵點擊「Dependencies」並選擇「管理 NuGet 套件」選項。

  3. 選擇「瀏覽」標籤,然後搜尋「IronPdf」。

  4. 選擇 IronPDF 並點擊“安裝”。

    或者,在 Visual Studio 中,您可以使用套件管理器主控台通過執行以下命令來安裝該庫:

Install-Package IronPdf
Install-Package IronPdf
'INSTANT VB TODO TASK: The following line uses invalid syntax:
'Install-Package IronPdf
$vbLabelText   $csharpLabel

IronPDF 與 LiteDB 的示例用法

這裡有一個簡單的代碼範例,說明如何使用IronPDF從HTML內容生成PDF,並使用'using'語句來確保正確的資源處理。 在這裡,我們結合了LiteDB和IronPDF的功能,展示如何將LiteDB中的資料輸出為PDF以供檢視。

using DemoLiteDB1;
using LiteDB;
using System.Text;
class Program
{
    static void Main()
    {
        using (var db = new LiteDatabase(@"MyData.db"))
        {
            var products = db.GetCollection<Product>("products");
            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 }
            };
            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)
    {
        IronPdf.License.LicenseKey = "Your-License-Key";
        Console.WriteLine("PDF Generating Started...");
        var renderer = new ChromePdfRenderer();
        Console.WriteLine("PDF Processing ....");
        var pdf = renderer.RenderHtmlAsPdf(data);
        string filePath = "Data.pdf";
        pdf.SaveAs(filePath);
        Console.WriteLine($"PDF Generation Completed, File Saved as {filePath}");
    }
    public static string GenerateHtml(List<Product> products)
    {
        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>");
        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 DemoLiteDB1;
using LiteDB;
using System.Text;
class Program
{
    static void Main()
    {
        using (var db = new LiteDatabase(@"MyData.db"))
        {
            var products = db.GetCollection<Product>("products");
            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 }
            };
            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)
    {
        IronPdf.License.LicenseKey = "Your-License-Key";
        Console.WriteLine("PDF Generating Started...");
        var renderer = new ChromePdfRenderer();
        Console.WriteLine("PDF Processing ....");
        var pdf = renderer.RenderHtmlAsPdf(data);
        string filePath = "Data.pdf";
        pdf.SaveAs(filePath);
        Console.WriteLine($"PDF Generation Completed, File Saved as {filePath}");
    }
    public static string GenerateHtml(List<Product> products)
    {
        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>");
        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();
    }
}
IRON VB CONVERTER ERROR developers@ironsoftware.com
$vbLabelText   $csharpLabel

該程式碼連接到一個LiteDB資料庫,新增一個產品清單,檢索所有產品,並生成產品清單的HTML表示。然後使用IronPDF庫將此HTML內容用於創建PDF文件。 過程包括添加產品、提取產品、將產品列表轉換為HTML以及生成PDF的方法。

輸出

LiteDB .NET(其如何為開發人員工作):圖 3 - 來自前述代碼的控制台輸出

PDF檔案輸出

LiteDB .NET(它對開發人員的作用):圖 4 - 上述代碼生成的 PDF

結論

LiteDB 為 C# 開發人員提供了一種輕量化、無伺服器的嵌入式文件數據庫解決方案,非常適合小型專案和行動應用程式,具有 MongoDB 啟發的 API、嵌入式數據庫和跨平台兼容等特色。

同時,IronPDF 成為首屈一指的 C# PDF 庫,通過其 HTML 到 PDF 轉換和 NuGet 集成,簡化了.NET 專案中的 PDF 生成和操作。 LiteDB 和 IronPDF 都為開發人員提供了有用的工具,其中 LiteDB 在資料庫管理方面表現優異,而 IronPDF 則在 PDF 處理方面表現出色。

IronPDF 提供免費試用,以釋放其在 PDF 生成和操作中的全部潛力。

Chipego
奇佩戈·卡林达
軟體工程師
Chipego 擁有天生的傾聽技能,這幫助他理解客戶問題,並提供智能解決方案。他在獲得信息技術理學學士學位後,于 2023 年加入 Iron Software 團隊。IronPDF 和 IronOCR 是 Chipego 專注的兩個產品,但隨著他每天找到新的方法來支持客戶,他對所有產品的了解也在不斷增長。他喜歡在 Iron Software 的協作生活,公司內的團隊成員從各自不同的經歷中共同努力,創造出有效的創新解決方案。當 Chipego 離開辦公桌時,他常常享受讀好書或踢足球的樂趣。
< 上一頁
RestEase C#(它對開發者的運作方式)
下一個 >
FireSharp C# (對開發者而言的運作方式)