I have this object model:
PhoneBookContact contact2 = new()
{
//Id = ObjectId.GenerateNewId().ToString(),
FirstName = "contact 2",
Location = "Bern",
PhoneBookIds= [], //Ids of another collection
Numbers = [
new PhoneBookContactNumber { /*Id = ObjectId.GenerateNewId().ToString(),*/ Number = "+41580000003", Type = NumberType.Office },
new PhoneBookContactNumber { /*Id = ObjectId.GenerateNewId().ToString(),*/ Number = "+41760000004", Type = NumberType.Mobile }
]
};
All properties called Id
are strings, but should be stored as ObjectId in the database. Do do this for all Id properties in all collections, I’m using a Convention
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));
}
}
To treat the PhoneBookIds, I’m doing this:
classMap.MapProperty(x => x.PhoneBookIds)
.SetSerializer(
new EnumerableInterfaceImplementerSerializer<List<string>, string>(
new StringSerializer(BsonType.ObjectId)));
Now I’d like to have the same treatment for PhoneBookContactNumber.Id
. So I tried this:
classMap.MapProperty(x => x.Numbers[0].Number).SetSerializer(new StringSerializer(BsonType.ObjectId));
which doesn’t work. Any idea what I have to do to autogenerate the Id for that included subdocument?