2025-11-08
LiteDB
00

目录

序列化概述
Nuget 安装LiteDB包
基本序列化支持
高级序列化配置
忽略特定属性
自定义字段映射
复杂对象序列化
注意事项
结论

序列化概述

LiteDB 提供了强大且灵活的序列化机制,能够处理各种复杂的对象序列化场景。本文将深入探讨 LiteDB 的高级序列化特性和最佳实践。

Nuget 安装LiteDB包

image.png

基本序列化支持

LiteDB 默认支持多种 .NET 类型的序列化:

  • 基本类型(int, string, bool 等)
  • 复杂对象
  • 集合类型(List, Dictionary)
  • 枚举类型
  • 可空类型(Nullable)

高级序列化配置

忽略特定属性

在某些场景下,您可能希望在序列化过程中排除某些属性。LiteDB 提供了 Ignore 方法来实现这一需求。

C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using LiteDB; namespace App05 { public class DeviceInfo { [BsonId] // 明确标记 Id 字段 public int Id { get; set; } public string DeviceName { get; set; } // 利用特性进行忽略 [BsonIgnore] public object TemporaryData { get; set; } } }
C#
using System; using LiteDB; namespace App05 { internal class Program { static void Main(string[] args) { // 直接使用数据库,不需要额外配置 using (var db = new LiteDatabase("MyData.db")) { // 获取集合 var deviceCollection = db.GetCollection<DeviceInfo>("devices"); // 插入测试数据 var deviceInfo = new DeviceInfo { DeviceName = "Sample Device", TemporaryData = new { Note = "Some temporary data" } }; deviceCollection.Insert(deviceInfo); Console.WriteLine("插入成功,Id = " + deviceInfo.Id); // 查询所有数据 var allDevices = deviceCollection.FindAll(); foreach (var device in allDevices) { Console.WriteLine($"Id: {device.Id}, DeviceName: {device.DeviceName}"); } // 更新数据示例 deviceInfo.DeviceName = "Updated Device Name"; deviceCollection.Update(deviceInfo); // 查询单条记录 var singleDevice = deviceCollection.FindById(deviceInfo.Id); Console.WriteLine($"更新后单条记录: Id = {singleDevice.Id}, DeviceName = {singleDevice.DeviceName}"); // 删除数据示例 deviceCollection.Delete(deviceInfo.Id); Console.WriteLine("删除成功"); } Console.WriteLine("示例执行完毕,请查看控制台输出以及生成的 MyData.db 文件。"); Console.ReadLine(); } } }

image.png

自定义字段映射

您可以自定义属性在 BSON 文档中的键名,这在处理遗留系统或需要特定命名约定时非常有用。

C#
public class DeviceInfo { public int Id { get; set; } public string DeviceName { get; set; } } public class LiteDbSerializationConfig { public static void ConfigureSerializer() { // 自定义字段映射 BsonMapper.Global.Entity<DeviceInfo>() .Field(x => x.DeviceName, "name") // 将 DeviceName 映射为 "name" .Field(x => x.Id, "_id"); // 将 Id 映射为 "_id" } }
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using LiteDB; namespace App05 { // 设备管理类 public class DeviceManager { private readonly string _dbPath; public DeviceManager(string dbPath) { _dbPath = dbPath; } // 添加设备 public void AddDevice(DeviceInfo device) { using (var db = new LiteDatabase(_dbPath)) { var collection = db.GetCollection<DeviceInfo>("devices"); collection.Insert(device); } } // 获取所有设备 public List<DeviceInfo> GetAllDevices() { using (var db = new LiteDatabase(_dbPath)) { var collection = db.GetCollection<DeviceInfo>("devices"); return collection.FindAll().ToList(); } } // 根据ID获取设备 public DeviceInfo GetDeviceById(int id) { using (var db = new LiteDatabase(_dbPath)) { var collection = db.GetCollection<DeviceInfo>("devices"); return collection.FindById(id); } } // 更新设备信息 public bool UpdateDevice(DeviceInfo device) { using (var db = new LiteDatabase(_dbPath)) { var collection = db.GetCollection<DeviceInfo>("devices"); return collection.Update(device); } } // 删除设备 public bool DeleteDevice(int id) { using (var db = new LiteDatabase(_dbPath)) { var collection = db.GetCollection<DeviceInfo>("devices"); return collection.Delete(id); } } } }
C#
using System; using LiteDB; namespace App05 { internal class Program { static void Main(string[] args) { // 配置序列化 LiteDbSerializationConfig.ConfigureSerializer(); // 创建设备管理器实例 var deviceManager = new DeviceManager("devices.db"); // 添加设备 var device = new DeviceInfo { Id = 1, DeviceName = "测试设备" }; deviceManager.AddDevice(device); // 获取设备 var savedDevice = deviceManager.GetDeviceById(1); Console.WriteLine($"设备ID: {savedDevice.Id}, 设备名称: {savedDevice.DeviceName}"); // 更新设备 savedDevice.DeviceName = "已更新的设备名称"; deviceManager.UpdateDevice(savedDevice); // 获取所有设备 var allDevices = deviceManager.GetAllDevices(); foreach (var d in allDevices) { Console.WriteLine($"设备ID: {d.Id}, 设备名称: {d.DeviceName}"); } Console.WriteLine("示例执行完毕,请查看控制台输出以及生成的 devices.db 文件。"); Console.ReadLine(); } } }

image.png

image.png

复杂对象序列化

对于包含嵌套对象和集合的复杂类型,LiteDB 提供了灵活的序列化机制。

C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace App05 { // 定义复杂设备类 public class ComplexDevice { public int Id { get; set; } public string Name { get; set; } public List<Sensor> Sensors { get; set; } public DeviceConfiguration Configuration { get; set; } } // 传感器类 public class Sensor { public string Type { get; set; } public double Value { get; set; } } // 设备配置类 public class DeviceConfiguration { public bool IsEnabled { get; set; } public Dictionary<string, string> Parameters { get; set; } } }
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using LiteDB; namespace App05 { public class SerializationDemo { public void DemonstrateComplexSerialization() { try { // 配置序列化映射 var mapper = new BsonMapper(); // 创建示例设备对象 var device = new ComplexDevice { Name = "Smart Sensor Hub", Sensors = new List<Sensor> { new Sensor { Type = "Temperature", Value = 25.5 }, new Sensor { Type = "Humidity", Value = 60.0 } }, Configuration = new DeviceConfiguration { IsEnabled = true, Parameters = new Dictionary<string, string> { { "Mode", "Advanced" }, { "Interval", "5000" } } } }; // 使用配置的mapper创建数据库连接 using (var db = new LiteDatabase(@"MyDatabase.db", mapper)) { // 获取集合 var collection = db.GetCollection<ComplexDevice>("devices"); // 创建索引 collection.EnsureIndex(x => x.Name); // 插入数据 collection.Insert(device); // 读取示例 var savedDevice = collection.FindById(device.Id); if (savedDevice != null) { Console.WriteLine($"Retrieved device: {savedDevice.Name}"); Console.WriteLine("Sensors:"); foreach (var sensor in savedDevice.Sensors) { Console.WriteLine($"- {sensor.Type}: {sensor.Value}"); } Console.WriteLine($"Configuration Enabled: {savedDevice.Configuration.IsEnabled}"); Console.WriteLine("Configuration Parameters:"); foreach (var param in savedDevice.Configuration.Parameters) { Console.WriteLine($"- {param.Key}: {param.Value}"); } } // 更新示例 device.Name = "Updated Smart Sensor Hub"; collection.Update(device); // 查找所有设备 var allDevices = collection.FindAll(); foreach (var dev in allDevices) { Console.WriteLine($"Device: {dev.Name}"); } } } catch (Exception ex) { Console.WriteLine($"Error occurred: {ex.Message}"); Console.WriteLine($"Stack Trace: {ex.StackTrace}"); } } } }
C#
using System; using LiteDB; namespace App05 { internal class Program { static void Main(string[] args) { var demo = new SerializationDemo(); demo.DemonstrateComplexSerialization(); Console.ReadLine(); } } }

image.png

注意事项

  1. 尽量使用属性特性(如 [BsonIgnore])进行简单的序列化控制
  2. 对于复杂的序列化需求,使用 BsonMapper.Global 进行全局配置
  3. 避免在序列化过程中包含敏感或大量的临时数据
  4. 定期审查和优化序列化配置,确保性能和数据完整性

结论

LiteDB 的高级序列化功能为开发者提供了强大且灵活的数据存储解决方案。通过合理配置和自定义,您可以精确控制对象的序列化行为。

本文作者:技术老小子

本文链接:

版权声明:本博客所有文章除特别声明外,均采用 BY-NC-SA 许可协议。转载请注明出处!