Search code examples
c#.netmongodbmongodb-.net-driver

Mongo do not generate ObjectId automatically via fulent API


I'm migrating from Mongo Driver 1.x to 2.x and encountered with a problem that Mongo do not simply generate the ID for a document.

Entity:

public sealed class History
{
    public string Id { get; set; }
    public long BusinessId { get; set; }
    public ShowcaseVersion Version { get; set; }
}

Mapping:

cm.AutoMap();
cm.MapIdMember(c => c.Id)
    .SetIgnoreIfDefault(true)
    .SetSerializer(new StringSerializer(BsonType.ObjectId))
    .SetIdGenerator(StringObjectIdGenerator.Instance)

Insert:

Collection.InsertOne(new History
{
    BusinessId = businessId,
    Version = version
});

Result:

E11000 duplicate key error collection: showcases.History index: id dup key: { : null }


Solution

  • If you want to go for ObjectId instead string than change it to ObjectId and I think it should work.

    But if you want to use string like you do this post might be answer: using string for mongodb _id