Using MongoDB I want to keep my model 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 run I get a null reference exception on the IdMemberMap. Can someone please tell me if something is wrong?
This is borderline to being a bug in the C# driver. Turns out IdMemberMap is not defined until the class map is “frozen”, for reasons having to do with class hierarchies in which the Id might actually be defined in a base class. One way to work around this is:
Another way to work around is to use GetMemberMap instead of IdMemberMap: