mongodbmongodb-.net-driver

MongoDB id remains null after InsertOneAsync


I have a base class Entity that has a string Id member and a derived class A.

But when creating a new instance of the derived class and using InsertOneAsync to add it to my collection, the document is added to the database with null as the Id value.

Using an ObjectId as the Id does seem to work, but I'm trying to prevent MongoDB dependency in my models.

I also experimented with the following code, but the results are the same:

BsonClassMap.RegisterClassMap<Entity>(cm =>
{
    cm.MapIdField(x => x.Id).SetSerializer(new StringSerializer(BsonType.ObjectId));
});

Solution

  • I had the same issue and finally got it to work (with the 2.0 driver) with these attributes:

    [BsonId]
    [BsonRepresentation(BsonType.ObjectId)]
    [BsonIgnoreIfDefault]
    

    Or the equivalent BsonClassMap fluent interface:

    BsonClassMap.RegisterClassMap<Entity>(cm =>
    {
          cm.MapIdField(x => x.Id)
          .SetSerializer(new StringSerializer(BsonType.ObjectId))
          .SetIgnoreIfDefault(true);
    });
    

    I tried to get the same working with .ReplaceOneAsync with Upsert on but that always leaves the id still null