LiteDb簡單key-value pair存法
LiteDb是C#上簡單的NoSql資料庫,不過想用一個collection來存不同型別的key-value pair就略顯麻煩。
好在LiteDb本身有提供schema-less的用法,詳細可參閱Collections - LiteDB :: A .NET embedded NoSQL database。
再略微調整一下,就可以撰寫一個通用的key-value pair存法。
Base class如下
public class KeyValueRepository
{
public KeyValueRepository(ILiteCollection<BsonDocument> collection)
{
_collection = collection;
}
private ILiteCollection<BsonDocument> _collection;
protected void SetValue(string key, object? value)
{
_collection.Upsert(new BsonDocument { ["_id"] = key, ["Value"] = BsonMapper.Global.Serialize(value) });
}
protected T? GetValue<T>(string key)
{
return BsonMapper.Global.Deserialize<T>(_collection.FindById(key)?["Value"]);
}
}
繼承後,要宣告不同的type就比較方便了。
public class MyRepository : KeyValueRepository
{
public MyRepository(ILiteCollection<BsonDocument> collection) : base(collection) { }
public int A
{
get => GetValue<int>(nameof(A));
set => SetValue(nameof(A), value);
}
public string? B
{
get => GetValue<string>(nameof(B));
set => SetValue(nameof(B), value);
}
public List<int>? C
{
get => GetValue<List<int>>(nameof(C));
set => SetValue(nameof(C), value);
}
public Dictionary<string, int>? D
{
get => GetValue<Dictionary<string, int>>(nameof(D));
set => SetValue(nameof(D), value);
}
public Custom? E
{
get => GetValue<Custom>(nameof(E));
set => SetValue(nameof(E), value);
}
}
public class Custom
{
public int Haha { get; set; }
public string Hoho { get; set; }
}
最後用起來的樣子
using LiteDB;
// Open database (or create if doesn't exist)
using var ms = new MemoryStream();
using var db = new LiteDatabase(ms);
// Get a collection (or create, if doesn't exist)
var col = db.GetCollection<BsonDocument>("trytrysee");
var data = new MyRepository(col);
data.A = 123;
data.B = "123456";
data.C = new List<int> { 1, 3, 5, 7, 9 };
data.D = new Dictionary<string, int> { ["hello"] = 123, ["world"] = 456, };
data.E = new Custom { Haha = 777, Hoho = "Hoho" };
Console.WriteLine(data.A);
Console.WriteLine(data.B);
Console.WriteLine(data.C.Select(v => v.ToString()).Join(","));
Console.WriteLine(data.D.Select(v => $"{v.Key}:{v.Value}").Join(","));
Console.WriteLine($"Haha:{data.E.Haha}, Hoho:{data.E.Hoho}");
留言
張貼留言