1 回答
TA贡献1906条经验 获得超3个赞
您需要注册一个新的序列化程序来处理您的 senario,幸好这个库是非常可扩展的,所以您只需要编写一些需要扩展的部分。
因此,首先您需要创建一个Serializer将您的字符串键写为下划线大小写的:
public class UnderscoreCaseStringSerializer : StringSerializer
{
public override void Serialize(BsonSerializationContext context, BsonSerializationArgs args, string value)
{
value = string.Concat(value.Select((x, i) => i > 0 && char.IsUpper(x) ? "_" + x.ToString() : x.ToString())).ToLower();
base.Serialize(context, args, value);
}
}
现在我们有了一个可以使用的序列化器,我们可以在 bson 序列化器注册表中注册一个新的字典序列化器,并将我们的新序列化器UnderscoreCaseStringSerializer用于序列化密钥:
var customSerializer =
new DictionaryInterfaceImplementerSerializer<Dictionary<string, string>>
(DictionaryRepresentation.Document, new UnderscoreCaseStringSerializer(), new ObjectSerializer());
BsonSerializer.RegisterSerializer(customSerializer);
就是这样......
internal class MyDocument
{
public ObjectId Id { get; set; }
public string Name { get; set; }
public Dictionary<string, string> AdditionalData { get; set; }
}
var collection = new MongoClient().GetDatabase("test").GetCollection<MyDocument>("docs");
var myDocument = new MyDocument
{
Name = "test",
AdditionalData = new Dictionary<string, string>
{
["boardId"] = "149018"
}
};
collection.InsertOne(myDocument);
// { "_id" : ObjectId("5b74093fbbbca64ba8ce9d0e"), "name" : "test", "additional_data" : { "board_id" : "149018" } }
您可能还想考虑使用 aConventionPack来处理您的字段名称使用下划线的约定,这只是意味着您不需要用BsonElement属性乱扔类,它只是按照约定工作。
public class UnderscoreCaseElementNameConvention : ConventionBase, IMemberMapConvention
{
public void Apply(BsonMemberMap memberMap)
{
string name = memberMap.MemberName;
name = string.Concat(name.Select((x, i) => i > 0 && char.IsUpper(x) ? "_" + x.ToString() : x.ToString())).ToLower();
memberMap.SetElementName(name);
}
}
var pack = new ConventionPack();
pack.Add(new UnderscoreCaseElementNameConvention());
ConventionRegistry.Register(
"My Custom Conventions",
pack,
t => true);
- 1 回答
- 0 关注
- 152 浏览
添加回答
举报