
LiteDB .NET(开发者用法)
LiteDB 是一个简单、快速且轻量级的嵌入式 .NET 文档数据库。 LiteDB .NET 受 MongoDB 数据库启发,其 API 与 MongoDB 的官方 .NET API 非常相似。 LiteDB 是一个无服务器数据库,非常适合小型项目和移动应用程序。
本文将为您提供准确的说明,帮助您在项目中利用 LiteDB 的功能。 我们还介绍了使用由Iron Software开发的.NET库IronPDF来生成和操作PDF,以及如何应用它将LiteDB数据库的内容输出为PDF以便查看和共享。
LiteDB 的主要特性
- **嵌入式数据库:**不需要单独的服务器。 LiteDB 在您的应用程序进程内运行。
- **单一数据文件:**您可以将所有数据存储在一个单文件数据库中,简化部署和备份。
- **BSON 格式:**使用 BSON 格式进行存储,确保快速读写操作。
- **LINQ 支持:**完全支持 LINQ 查询,使 .NET 开发人员更直观。
- **ACID 事务:**通过支持 ACID 事务确保数据完整性。
- **跨平台:**支持 Windows、Linux 和 macOS。
在 .NET 项目中设置 LiteDB
在 Visual Studio 中打开你的项目。 然后,在解决方案资源管理器中,右键单击您的项目并选择"管理 NuGet 包"。搜索 LiteDB 并安装它,将此数据库解决方案轻松集成到您的项目中。
或者,您可以通过使用包管理器控制台进行安装。 要在 NuGet 包管理器控制台中安装 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 Property Id As Integer
Public Property Name As String
Public Property Price As Decimal
End Class接下来,我们将创建一个数据库并插入一些产品:
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代码描述
代码初始化了一个名为"MyData.db"的LiteDB数据库的连接,并检索了名为"products"的集合。然后它创建了一个包含各种属性(如ID、Name和Price)的Product对象数组。数组中的每个产品都插入到数据库内的"products"集合中。 成功插入所有产品后,它会在控制台上打印确认消息。
输出如:

示例:优化用户数据管理
假设您正在开发一个管理用户帐户的移动应用程序。 每个用户都有一个包含其姓名、电子邮件地址、偏好(存储为 JSON 对象)和收藏项目列表的资料。 以下是 LiteDb.NET 如何简化您的数据存储:
此代码定义了一个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);
}
}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此实现有效利用 LiteDb.NET 的功能来管理用户数据。 UserManager类提供了在数据库中保存、检索、更新和删除用户的方法。
LiteDB, 为 .NET 提供的嵌入式 NoSQL 数据库
LiteDB 非常适合不需要用户并发的小型到中型应用程序。 例如,它非常适合个人控制台应用程序,您希望简单快捷地存储数据。 完全用 C# 开发,轻量级,占用小于 450KB,并且不依赖外部依赖项。
一些更多的要点,列在他们的GitHub 页面上:
- 无服务器 NoSQL 文档存储
- 类似于 MongoDB 的简单 API
- 线程安全
- 完全用 C# 编写,LiteDB 与 .NET 4.5、NETStandard 1.3/2.0 兼容,打包成一个小于 450KB 的单个 DLL 文件。
- 支持完整事务的 ACID
- 写入失败后的数据恢复(WAL 日志文件)
- 使用 AES 加密技术进行数据文件加密
- 您可以使用 LiteDB 提供的属性或流畅映射 API,轻松将您简单的旧 CLR 对象(POCO)类映射到 BsonDocument。
- 存储文件和流数据(如 MongoDB 中的 GridFS)
- 单一数据文件存储(如 SQLite)
- 为快速搜索索引文档字段
- 用于查询的 LINQ 支持
- 访问/转换数据的类 SQL 命令
- LiteDB Studio – 用于数据访问的优秀 UI
- 开源且对所有人免费 – 包括用于商业用途
IronPDF简介:一个 C# 的PDF库

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 包管理器安装该库。 然后只需遵循以下简单步骤:
- 打开 Visual Studio 并导航到解决方案资源管理器。
- 右键单击依赖项并选择"管理 NuGet 包"选项。
- 选择"浏览"标签并搜索"IronPDF"。
- 选择 IronPDF 并点击"安装"。
或者,在 Visual Studio 中,您可以使用包管理器控制台通过以下命令安装库:
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();
}
}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该代码连接到一个 LiteDB 数据库,添加一个产品列表,检索所有产品,并生成产品列表的 HTML 表示。然后,该 HTML 内容用于使用 IronPDF 库创建一个 PDF 文件。 该过程包括添加产品、获取产品、将产品列表转换为 HTML 和生成 PDF 的方法。
输出

PDF 文件输出

结论
LiteDB 为 C# 开发人员提供了一个轻量级、无服务器嵌入式文档数据库解决方案,理想用于小型项目和移动应用程序,具有 MongoDB 启发的 API、嵌入式数据库和跨平台兼容性等特性。
同时,IronPDF作为首屈一指的 C# PDF 库出现,在 .NET 项目中通过 HTML 到 PDF 转换和 NuGet 集成简化 PDF 的生成和操作。 LiteDB 和 IronPDF 都为开发人员提供了有价值的工具,LiteDB 在数据库管理中表现出色,而 IronPDF 在 PDF 处理方面表现突出。
IronPDF 提供免费试用以释放其在 PDF 生成和操作中的全部潜力。

Jacob Mellor 是 Iron Software 的首席技术官,也是一位开创 C# PDF 技术的有远见的工程师。作为 Iron Software 核心代码库的原始开发者,他从公司成立之初就开始塑造公司的产品架构,与首席执行官 Cameron Rimington 一起将公司转变为一家拥有 50 多名员工的公司,为 NASA、特斯拉和全球政府机构提供服务。
相关文章


