跳至页脚内容
.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; }
}
IRON VB CONVERTER ERROR developers@ironsoftware.com
$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.");
        }
    }
}
Imports LiteDB
Imports System

Friend Class Program
	Shared Sub Main()
		' Open the database (or create it if it doesn't exist)
		Using db = New LiteDatabase("MyData.db")
			' Get a collection (or create, if it doesn't exist)
			Dim products = db.GetCollection(Of Product)("products")

			' Create a list of products to insert into the database
			Dim productList = {
				New Product With {
					.Id = 201,
					.Name = "Apple",
					.Price = 0.99D
				},
				New Product With {
					.Id = 202,
					.Name = "Banana",
					.Price = 0.59D
				},
				New Product With {
					.Id = 203,
					.Name = "Orange",
					.Price = 0.79D
				},
				New Product With {
					.Id = 204,
					.Name = "Grape",
					.Price = 2.99D
				},
				New Product With {
					.Id = 205,
					.Name = "Watermelon",
					.Price = 4.99D
				}
			}

			' Insert each product into the collection
			For Each product In productList
				products.Insert(product)
			Next product

			Console.WriteLine("Product inserted successfully.")
		End Using
	End Sub
End Class
$vbLabelText   $csharpLabel

代码描述

该代码初始化一个名为“MyData.db”的 LiteDB 数据库连接,并检索一个名为“products”的集合。然后,它创建一个包含各种属性(如 ID、名称和价格)的 Product 对象数组。数组中的每个产品都被插入到数据库中的“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);
    }
}
Imports LiteDB
Imports System.Collections.Generic

Public Class User
	<BsonId>
	Public Property Id() As String
	Public Property Name() As String
	Public Property Email() As String
	Public Property Preferences() As Dictionary(Of String, String)
	Public Property FavoriteItems() As List(Of String)
End Class

Public Class UserManager
	Private ReadOnly db As LiteDatabase

	Public Sub New(ByVal connectionString As String)
	   db = New LiteDatabase(connectionString)
	End Sub

	Public Sub SaveUser(ByVal user As User)
		Dim collection = db.GetCollection(Of User)("users")
		collection.Insert(user)
	End Sub

	Public Function GetUser(ByVal userId As String) As User
		Dim collection = db.GetCollection(Of User)("users")
		Return collection.FindById(userId)
	End Function

	Public Sub UpdateUser(ByVal user As User)
		Dim collection = db.GetCollection(Of User)("users")
		collection.Update(user)
	End Sub

	Public Sub DeleteUser(ByVal userId As String)
		Dim collection = db.GetCollection(Of User)("users")
		collection.Delete(userId)
	End Sub
End Class
$vbLabelText   $csharpLabel

此实现有效利用 LiteDb.NET 的功能来管理用户数据。 User 类存储用户信息,而 UserManager 类提供方法来在数据库中保存、检索、更新和删除用户。

LiteDB, 为 .NET 提供的嵌入式 NoSQL 数据库

LiteDB 非常适合不需要用户并发的小型到中型应用程序。 例如,它非常适合个人控制台应用程序,您希望简单快捷地存储数据。 完全用 C# 开发,轻量级,占用小于 450KB,并且不依赖外部依赖项。

一些更多的要点,列在他们的GitHub 页面上:

  1. 无服务器 NoSQL 文档存储
  2. 类似于 MongoDB 的简单 API
  3. 线程安全
  4. 完全用 C# 编写,LiteDB 与 .NET 4.5、NETStandard 1.3/2.0 兼容,打包成一个小于 450KB 的单个 DLL 文件。
  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, a premier C# PDF library, facilitates seamless creation, editing, and IronPDF,一个首屈一指的 C# PDF 库,方便无缝地在 .NET 项目中创建编辑操作 PDF。 它为HTML 到 PDF转换、动态 PDF 生成和数据提取等任务提供了全面的 API。 利用 .NET Chromium 引擎确保准确地将 HTML 渲染为 PDF 文件,满足 .NET Core、.NET Standard 和 .NET Framework 的多样化项目需求。 IronPDF 保证从 HTML 内容生成 PDF 的精确性、简便性和效率,支持网页、桌面和控制台应用。

安装 IronPDF 库

要在项目中启动 IronPDF,请通过 Visual Studio 中的 NuGet 包管理器安装该库。 然后只需遵循以下简单步骤:

  1. 打开 Visual Studio 并导航到解决方案资源管理器。
  2. 右键单击依赖项并选择“管理 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();
    }
}
Imports LiteDB
Imports System
Imports System.Collections.Generic
Imports System.Linq
Imports System.Text
Imports IronPdf

Friend Class Program
	Shared Sub Main()
		Using db = New LiteDatabase("MyData.db")
			' Retrieve the 'products' collection or create it
			Dim products = db.GetCollection(Of Product)("products")

			' Add some initial products to the collection
			Dim productList = {
				New Product With {
					.Id = 101,
					.Name = "Apple",
					.Price = 0.99D
				},
				New Product With {
					.Id = 102,
					.Name = "Banana",
					.Price = 0.59D
				},
				New Product With {
					.Id = 103,
					.Name = "Orange",
					.Price = 0.79D
				},
				New Product With {
					.Id = 104,
					.Name = "Grape",
					.Price = 2.99D
				},
				New Product With {
					.Id = 105,
					.Name = "Watermelon",
					.Price = 4.99D
				}
			}

			' Insert products into the LiteDB collection
			For Each product In productList
				products.Insert(product)
			Next product

			Console.WriteLine("Product inserted successfully.")

			' Fetch all products from the database
			Dim allProducts = GetAllProducts(db)

			' Generate HTML content from the product list
			Dim htmlContent As String = GenerateHtml(allProducts)

			' Generate the PDF from the HTML content
			GeneratePDF(htmlContent)

			Console.WriteLine("PDF generated successfully.")
		End Using
	End Sub

	Public Shared Function GetAllProducts(ByVal db As LiteDatabase) As List(Of Product)
		Dim products = db.GetCollection(Of Product)("products")
		Return products.FindAll().ToList()
	End Function

	Public Shared Sub GeneratePDF(ByVal data As String)
		' Set your IronPDF license key here
		IronPdf.License.LicenseKey = "Your-License-Key"
		Console.WriteLine("PDF Generating Started...")

		' Create a PDF renderer
		Dim renderer = New ChromePdfRenderer()
		Console.WriteLine("PDF Processing ....")

		' Render the HTML as a PDF
		Dim pdf = renderer.RenderHtmlAsPdf(data)

		' Save the PDF to a file
		Dim filePath As String = "Data.pdf"
		pdf.SaveAs(filePath)

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

	Public Shared Function GenerateHtml(ByVal products As List(Of Product)) As String
		' Build HTML table from product list
		Dim htmlBuilder As 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
		For Each product In products
			htmlBuilder.Append($"<tr><td>{product.Id}</td><td>{product.Name}</td><td>{product.Price:C}</td></tr>")
		Next product

		htmlBuilder.Append("</table></body></html>")
		Return htmlBuilder.ToString()
	End Function
End Class
$vbLabelText   $csharpLabel

该代码连接到一个 LiteDB 数据库,添加一个产品列表,检索所有产品,并生成产品列表的 HTML 表示。然后,该 HTML 内容用于使用 IronPDF 库创建一个 PDF 文件。 该过程包括添加产品、获取产品、将产品列表转换为 HTML 和生成 PDF 的方法。

输出

LiteDB .NET(如何为开发人员工作):图 3 - 上述代码的控制台输出

PDF 文件输出

LiteDB .NET(如何为开发人员工作):图 4 - 上述代码输出的 PDF

结论

LiteDB 为 C# 开发人员提供了一个轻量级、无服务器嵌入式文档数据库解决方案,理想用于小型项目和移动应用程序,具有 MongoDB 启发的 API、嵌入式数据库和跨平台兼容性等特性。

同时,IronPDF作为首屈一指的 C# PDF 库出现,在 .NET 项目中通过 HTML 到 PDF 转换和 NuGet 集成简化 PDF 的生成和操作。 LiteDB 和 IronPDF 都为开发人员提供了有价值的工具,LiteDB 在数据库管理中表现出色,而 IronPDF 在 PDF 处理方面表现突出。

IronPDF 提供免费试用以释放其在 PDF 生成和操作中的全部潜力。

常见问题解答

如何将 HTML 内容转换为 C# 中的 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文件。它提供了编辑、合并和从PDF中提取内容的功能,可以在C#应用程序中使用。

LiteDB可以用于移动应用程序吗?

是的,LiteDB特别适合于移动应用程序,因为它具有轻量级、无服务器的特性,并且能够在一个单一文件中存储数据。

LiteDB集成的一些常见故障排除步骤是什么?

LiteDB集成的常见故障排除步骤包括检查通过NuGet的正确安装,确保您的数据库文件路径可访问,并确认项目的.NET版本与LiteDB兼容。

如何使用LiteDB确保数据完整性?

LiteDB支持ACID事务,这可确保数据的完整性和可靠性。您可以使用事务来维护一致性并处理并发数据修改。

在.NET中使用IronPDF进行PDF生成的好处是什么?

IronPDF提供了易于HTML到PDF转换、高精度渲染和全面PDF操作功能等好处,使其成为在.NET应用程序中生成和处理PDF的理想工具。

Curtis Chau
技术作家

Curtis Chau 拥有卡尔顿大学的计算机科学学士学位,专注于前端开发,精通 Node.js、TypeScript、JavaScript 和 React。他热衷于打造直观且美观的用户界面,喜欢使用现代框架并创建结构良好、视觉吸引力强的手册。

除了开发之外,Curtis 对物联网 (IoT) 有浓厚的兴趣,探索将硬件和软件集成的新方法。在空闲时间,他喜欢玩游戏和构建 Discord 机器人,将他对技术的热爱与创造力相结合。