.NET 幫助

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

發佈 2024年8月13日
分享:

簡介

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
Install-Package LiteDB
IRON VB CONVERTER ERROR developers@ironsoftware.com
VB   C#

開始使用 LiteDB

安裝完成後,您可以開始在應用程式中使用 LiteDB。讓我們通過一些示例來說明其使用方法。

Example 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
VB   C#

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

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
VB   C#

代碼說明

該代碼初始化與名為「MyData.db」的LiteDB數據庫的連接,並檢索名為「products」的集合。然後,它創建一個具有各種屬性(例如ID、Name和Price)的Product物件數組。數組中的每個產品都插入到數據庫內的「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
VB   C#

此實現有效利用LiteDb.NET的功能來進行用戶資料管理。User類別存儲用戶資訊,而UserManager類別提供了在資料庫中保存、檢索、更新和刪除用戶的方法。

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

LiteDB 非常適合沒有用戶並發需求的小型到中型應用程序。例如,它非常適合個人的控制台應用程序,在那裡您想簡單快捷地存儲數據。它完全用 C# 開發,體積輕巧,佔用不到 450KB,並且不依賴外部依賴項。

更多的要點,列在他們GitHub 頁面1. 無伺服器 NoSQL 文檔存儲

  1. 簡單的 API,類似於 MongoDB

  2. 線程安全

  3. 完全用 C# 編寫,LiteDB 與 .NET 4.5, NETStandard 1.3/2.0 兼容,封裝成單個 DLL 文件,佔用空間不到 450KB。

  4. 支持完整事務的ACID

  5. 寫入失敗後數據恢復 (WAL 日誌檔案)

使用 DES 進行數據文件加密 (AES) 加密

  1. 您可以輕鬆映射您的普通 CLR 對象 (POCO) 使用屬性或LiteDB提供的fluent mapper API將類轉換為BsonDocument。

  2. 存儲文件和流數據 (像 MongoDB 中的 GridFS)

    1. 單一數據文件儲存 (像 SQLite)
  3. 索引文件字段以進行快速搜索

  4. 支持LINQ查詢

  5. 類SQL命令來訪問/轉換數據

  6. LiteDB Studio – 用於數據訪問的優美用戶界面

  7. 開源且免費供所有人使用——包括商業用途

關於 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
Install-Package IronPdf
'INSTANT VB TODO TASK: The following line uses invalid syntax:
'Install-Package IronPdf
VB   C#

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
VB   C#

該代碼連接到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 生成和操作中的全部潛力。

< 上一頁
RestEase C#(它對開發者的運作方式)
下一個 >
FireSharp C# (對開發者而言的運作方式)

準備開始了嗎? 版本: 2024.10 剛剛發布

免費 NuGet 下載 總下載次數: 10,993,239 查看許可證 >