I'm just trying out the C# driver and was following through the example in the 'Getting Satrted with CSharp Driver' page, except I wanted to use a string representation of the ObjectId.So I added:BsonClassMap.RegisterClassMap<Entity>(cm => { cm.AutoMap(); cm.IdMemberMap.SetRepresentation(BsonType.ObjectId); });However when I stepped through the code, the first entity inserted had an Id of null. I checked this using the mongo shell.So I tried changing the mapping line tocm.IdMemberMap.SetRepresentation(BsonType.ObjectId).SetIgnoreIfNull(true);That hack worked to the extent that the the entity gained an ObjectId (per mongo shell), but didn't populate the Id field in the code.Another post suggests that my initial code should have worked.So is this a bug, or just me being thick?ThanksMark
Thanks DaveC, but that didn't work...
public class Entity { public string Id { get; set; } public string Name { get; set; } }
BsonClassMap.RegisterClassMap<Entity>(cm => { cm.AutoMap(); cm.IdMemberMap.SetRepresentation(BsonType.ObjectId).SetIgnoreIfNull(true); }); var connectionString = "mongodb://localhost"; var client = new MongoClient(connectionString); var server = client.GetServer(); var database = server.GetDatabase("test"); var settings = new MongoCollectionSettings<Entity>(database, "entities"); settings.AssignIdOnInsert = true; var collection = database.GetCollection<Entity>("entities", settings); var entity = new Entity { Name = "Tom" }; collection.Insert(entity); var id = entity.Id;With the above an ObjectId is created, but is not passed back to the entity so id = null.
Thanks - that was what I was missing.
Perhaps the documentation could mention this extra requirement, where it mentions the SetRepresentation ( just for the dummies like me :-) )