跳過到頁腳內容
.NET幫助

LiteDB .NET(對開發者的解析)。

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

這篇文章將為您提供準確的指導,告訴您如何在您的專案中利用 LiteDB 的功能。 我們還介紹了 IronPDF 的使用,這是一個由 Iron Software 開發的 .NET 程式庫,用於生成和操作 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

開始使用 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; }
}
$vbLabelText   $csharpLabel

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

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

代碼說明

該代碼初始化了一個名為"MyData.db"的 LiteDB 資料庫的連接,並檢索一個名為"products"的集合。然後它創建一個 Product 對象的數組,擁有各種屬性,如 ID、Name 和 Price。數組中的每個產品都插入到資料庫中的"products"集合中。 成功插入所有產品後,它會在控制台中打印確認訊息。

輸出如下:

LiteDB .NET (開發者如何運作):圖 1 - 前述代碼的控制台輸出

範例:簡化用戶資料管理

想像一下,您正在開發一個管理用戶帳戶的行動應用程式。 每個用戶都有一個包含其姓名、電子郵件地址、偏好(儲存為 JSON 對象)和收藏項目列表的個人資料。 以下是 LiteDb.NET 如何簡化您的數據存儲:

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

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

這個實現有效地利用了 LiteDb.NET 的用戶數據管理能力。 User 類儲存用戶資訊,而 UserManager 類提供了在資料庫中保存、檢索、更新和刪除用戶的方法。

LiteDB,針對 .NET 的嵌入式 NoSQL 資料庫

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. 使用 AES 加密技術加密資料文件
  8. 您可以輕鬆地使用屬性或 LiteDB 提供的流暢映射 API,將您的常規 CLR 對象 (POCO) 類映射到 BsonDocument。
  9. 儲存文件及流式數據(如同 MongoDB 的 GridFS)
  10. 單一數據文件儲存(如 SQLite)
  11. 索引文檔字段以便快速搜索
  12. 支援 LINQ 查詢
  13. 類似 SQL 的命令來存取/轉換數據
  14. LiteDB Studio – 優秀的數據訪問 UI
  15. 開源並免費供所有人使用 – 包括商業用途

介紹 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 套件管理器安裝該程式庫。 然後只需按照以下簡單步驟進行:

  1. 打開 Visual Studio,然後導航到解決方案總管。
  2. 右鍵單擊 Dependencies,然後選擇"管理 NuGet 套件"選項。
  3. 選擇"瀏覽"標籤並搜尋"IronPdf"。
  4. 選擇 IronPDF 並點擊"安裝"。

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

Install-Package IronPdf

IronPDF 與 LiteDB 的使用範例

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

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

此代碼連接到一個 LiteDB 資料庫,添加一個產品列表,檢索所有產品,然後生成產品列表的 HTML 表示。使用 IronPDF 程式庫將該 HTML 內容生成 PDF 文件。 這個過程包括添加產品、獲取產品、將產品列表轉換為 HTML 和生成 PDF 的方法。

輸出

LiteDB .NET (開發者如何運作):圖 3 - 前述代碼的控制台輸出

PDF 文件輸出

LiteDB .NET (開發者如何運作):圖 4 - 前述代碼輸出的 PDF

結論

LiteDB 向 C# 開發者提供了一個輕量、無伺服器的嵌入式文件資料庫解決方案,適合小型專案和行動應用程式,並於其中擁有諸如 MongoDB 啟發的 API、嵌入式資料庫和跨平台相容性等特點。

同時,IronPDF 作為一個頂級的 C# PDF 程式庫出現,簡化了 .NET 專案內的 PDF 生成和操作,透過其 HTML 到 PDF 轉換和 NuGet 整合。 LiteDB 和 IronPDF 都為開發者提供了有價值的工具,LiteDB 在於數據庫管理方面表現優異,而 IronPDF 則在於 PDF 操作。

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

常見問題解答

如何在 C# 中將 HTML 內容轉換為 PDF?

您可以使用 IronPDF 在 C# 中將 HTML 內容轉換為 PDF。該庫提供了像 RenderHtmlAsPdf 這樣的方法,允許將 HTML 字串轉換為 PDF 文件。

將 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 中使用 IronPDF 生成 PDF 的好處是什麼?

IronPDF 提供了易於 HTML 到 PDF 轉換的好處,高渲染準確性和全面的 PDF 操作功能,使其在 .NET 應用中生成和處理 PDF 的理想選擇。

Jacob Mellor, Team Iron 首席技術官
首席技術官

Jacob Mellor是Iron Software的首席技術官,也是開創C# PDF技術的前瞻性工程師。作為Iron Software核心代碼庫的原始開發者,他自公司成立以來就塑造了公司的產品架構,並與CEO Cameron Rimington將公司轉型為服務NASA、Tesla以及全球政府機構的50多人公司。

Jacob擁有曼徹斯特大學土木工程一級榮譽學士學位(1998年–2001年)。他於1999年在倫敦開立首家軟體公司,並於2005年建立了他的第一個.NET組件,專注於解決Microsoft生態系統中的複雜問題。

他的旗艦作品IronPDF和Iron Suite .NET程式庫全球已獲得超過3000萬次NuGet安裝,他的基礎代碼不斷在全球各地驅動開發者工具。擁有25年以上的商業經驗和41年的編碼專業知識,Jacob仍然專注於推動企業級C#、Java和Python PDF技術的創新,同時指導下一代技術領導者。

鋼鐵支援團隊

我們每週 5 天,每天 24 小時在線上。
聊天
電子郵件
打電話給我