使用MongoDB时如何按惯例应用BsonRepresentation属性

我正在尝试将[BsonRepresentation(BsonType.ObjectId)]应用于表示为字符串的所有id,而不得不用属性装饰我的所有id。

我尝试添加StringObjectIdIdGeneratorConvention但似乎没有对它进行排序。

有任何想法吗?

是的,我也注意到了。 StringObjectIdIdGeneratorConvention的当前实现似乎由于某种原因而不起作用。 这是一个有效的:

 public class Person { public string Id { get; set; } public string Name { get; set; } } public class StringObjectIdIdGeneratorConventionThatWorks : ConventionBase, IPostProcessingConvention { ///  /// Applies a post processing modification to the class map. ///  /// The class map. public void PostProcess(BsonClassMap classMap) { var idMemberMap = classMap.IdMemberMap; if (idMemberMap == null || idMemberMap.IdGenerator != null) return; if (idMemberMap.MemberType == typeof(string)) { idMemberMap.SetIdGenerator(StringObjectIdGenerator.Instance).SetSerializer(new StringSerializer(BsonType.ObjectId)); } } } public class Program { static void Main(string[] args) { ConventionPack cp = new ConventionPack(); cp.Add(new StringObjectIdIdGeneratorConventionThatWorks()); ConventionRegistry.Register("TreatAllStringIdsProperly", cp, _ => true); var collection = new MongoClient().GetDatabase("test").GetCollection("persons"); Person person = new Person(); person.Name = "Name"; collection.InsertOne(person); Console.ReadLine(); } } 

您可以以编程方式注册要用于表示mongo文档的C#类。 注册时,您可以覆盖默认行为(例如,将id映射到字符串):

 public static void RegisterClassMap() where T : IHasIdField { if (!BsonClassMap.IsClassMapRegistered(typeof(T))) { //Map the ID field to string. All other fields are automapped BsonClassMap.RegisterClassMap(cm => { cm.AutoMap(); cm.MapIdMember(c => c.Id).SetIdGenerator(StringObjectIdGenerator.Instance); }); } } 

然后为要注册的每个C#类调用此函数:

 RegisterClassMap(); RegisterClassMap(); 

您要注册的每个类都必须实现IHasIdField接口:

 public class MongoDocType1 : IHasIdField { public string Id { get; set; } // ...rest of fields } 

需要注意的是,这不是一个全局解决方案,您仍然需要手动迭代您的类。