猿问

如何使用 c# 在骆驼情况下在 mongo 中保存文档?

如何在骆驼情况下在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; }


跃然一笑
浏览 153回答 1
1回答

一只名叫tom的猫

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