在驼峰式的情况下,如何在mongo中保存文档?现在,我正在尝试保存此内容:
"parent_template_id": "5aa7822ba6adf805741c5722",
"type": "Mutable",
"subject": {
"workspace_id": "5-DKC0PV8U",
"additional_data": {
"boardId": "149018",
}
但boardId转换为db中的board_id(蛇形)。 这是我在c#中的字段:
[BsonElement("additional_data")]
[BsonIgnoreIfNull]
public Dictionary<string, string> AdditionalData { get; set; }
答案 0 :(得分:1)
您需要注册一个新的序列化程序来处理您的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);
}
}
现在我们有了一个序列化器,可以使用新的UnderscoreCaseStringSerializer
在bson序列化器注册表中注册一个新的字典序列化器,用于序列化密钥:
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" } }
您可能还想考虑使用ConventionPack
处理带有下划线的字段名称的约定,这仅意味着您不需要乱扔带有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);