IdMemberMap is null using "View Serialization Options"

Using MongoDB I want my model to be as clean as possible, so I decided to follow this approach: http://www.mongodb.org/display/DOCS/CSharp+Driver+Serialization+Tutorial#CSharpDriverSerializationTutorial-RepresentationSerializationOptions

I have a class like:

public class Person { public string Name { get; set; } public string Id { get; set; } public Person() { } public Person(string name) { this.Name = name; } } 

And inside application_start I have

 BsonClassMap.RegisterClassMap<Person>(x => { x.AutoMap(); x.IdMemberMap.SetRepresentation(BsonType.ObjectId); }); 

But when it starts, I get a null reference exception in IdMemberMap . Can someone tell me if something is wrong?

+4
source share
2 answers

This borders on a bug in the C # driver. It turns out that IdMemberMap is not defined until the class map is frozen for reasons related to class hierarchies in which the Identifier can be defined in the base class. One way around this is:

 BsonClassMap.RegisterClassMap<Person>(cm => { cm.AutoMap(); cm.Freeze(); cm.IdMemberMap.SetRepresentation(BsonType.ObjectId); }); 

Another workaround is to use GetMemberMap instead of IdMemberMap:

 BsonClassMap.RegisterClassMap<Person>(cm => { cm.AutoMap(); cm.GetMemberMap(c => c.Id).SetRepresentation(BsonType.ObjectId); }); 
+4
source

Install the ID generator manually

It is not in the documentation , but you need to manually install the identifier generator:

 BsonClassMap.RegisterClassMap<Person>(cm => { cm.AutoMap(); cm.IdMemberMap.SetRepresentation(BsonType.ObjectId); cm.IdMemberMap.SetIdGenerator(StringObjectIdGenerator.Instance); } 

Source: https://groups.google.com/d/msg/mongodb-user/_pjCDXZ9hOk/9N23ARe0_rgJ

0
source

Source: https://habr.com/ru/post/1382093/


All Articles