.NET MAUI中如何用SQLite存储Dictionary类型数据?
在.NET MAUI中用sqlite-net-pcl存储Dictionary<DateTime, string>的方案
sqlite-net-pcl本身不直接支持Dictionary类型的存储,下面提供两种可行的实现方式,以及其他可选方案:
方法一:序列化JSON存储(Text Blob方式)
这种方式适合不需要单独查询字典中条目的场景,实现简单,把字典序列化为JSON字符串存到数据库字段中,读取时自动反序列化。
实现步骤
- 安装序列化库:可以用
System.Text.Json(.NET内置)或Newtonsoft.Json,根据需求选择对应的NuGet包安装。 - 修改
Addiction类,添加序列化/反序列化的包装属性:
using System.Text.Json; public class Addiction { [PrimaryKey, AutoIncrement] public int Id { get; set; } public string Name { get; set; } public DateTime CreationDate { get; set; } public DateTime LastResetDate { get; set; } // 业务层直接使用的字典,标记为不映射到数据库 [Ignore] public Dictionary<DateTime, string> Notes { get; set; } = new Dictionary<DateTime, string>(); // 数据库实际存储的JSON字符串,自动同步字典内容 public string NotesJson { get => JsonSerializer.Serialize(Notes); set => Notes = JsonSerializer.Deserialize<Dictionary<DateTime, string>>(value) ?? new Dictionary<DateTime, string>(); } }
如果用Newtonsoft.Json,替换序列化逻辑即可:
using Newtonsoft.Json; // ...其他属性不变 [Ignore] public Dictionary<DateTime, string> Notes { get; set; } = new Dictionary<DateTime, string>(); public string NotesJson { get => JsonConvert.SerializeObject(Notes); set => Notes = JsonConvert.DeserializeObject<Dictionary<DateTime, string>>(value) ?? new Dictionary<DateTime, string>(); }
使用方式
- 插入对象:直接给
Notes字典赋值,调用connection.InsertAsync(yourAddiction)即可,NotesJson会自动生成并存储。 - 查询对象:调用
connection.GetAsync<Addiction>(id)后,Notes属性会自动从NotesJson反序列化得到,直接使用即可。
方法二:使用关联表(一对多关系)
如果需要单独查询、修改字典中的某个条目,推荐用这种方式,把字典拆成独立的Note表,和Addiction建立一对多关联。
实现步骤
- 创建
Note实体类:
public class Note { [PrimaryKey, AutoIncrement] public int Id { get; set; } public DateTime NoteDate { get; set; } public string Content { get; set; } // 外键,关联对应的Addiction记录 [ForeignKey(typeof(Addiction))] public int AddictionId { get; set; } }
- 修改
Addiction类,添加一对多关联:
using SQLiteNetExtensions.Attributes; public class Addiction { [PrimaryKey, AutoIncrement] public int Id { get; set; } public string Name { get; set; } public DateTime CreationDate { get; set; } public DateTime LastResetDate { get; set; } // 关联Note集合,设置级联操作自动同步增删改 [OneToMany(CascadeOperations = CascadeOperation.All)] public List<Note> Notes { get; set; } = new List<Note>(); // 可选:包装成Dictionary方便业务层使用 [Ignore] public Dictionary<DateTime, string> NotesDictionary { get => Notes.ToDictionary(n => n.NoteDate, n => n.Content); set { Notes.Clear(); Notes.AddRange(value.Select(kv => new Note { NoteDate = kv.Key, Content = kv.Value })); } } }
使用方式
- 插入对象:给
NotesDictionary赋值,或者直接操作Notes集合,调用SQLiteNetExtensions提供的connection.InsertWithChildrenAsync(yourAddiction)。 - 查询对象:调用
connection.GetWithChildrenAsync<Addiction>(id),会自动加载关联的Note数据,通过NotesDictionary即可按字典方式访问。
其他可选方案
- 文件存储:直接把整个
Addiction对象序列化为JSON/XML文件,存在本地文件系统,适合数据量不大的场景。 - Entity Framework Core for SQLite:EF Core支持更复杂的类型映射,包括通过值转换器处理
Dictionary,但学习成本略高。 - Preferences存储:仅适合极小的数据量,把字典序列化后存在Preferences中。
内容的提问来源于stack exchange,提问作者Pedro Schuster
相关产品推荐
相关产品推荐

