Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

333
Views
Get _id of an inserted document in MongoDB when using BsonClassMap?

Before anyone marks this question as a duplicate of Get _id of an inserted document in MongoDB? please read the whole question.

I am developing a ASP.NET Core API app with MongoDB driver.

The problem I am facing is that after inserting a document in the database the Id property of the Post class is not assigned the id generated by MongoDB.

I found few questions where they solved it using the annotations/attributes in the class but, I am developing a pattern where domain classes don't have any persistence knowledge.

I have created the entity class without annotations:

public class Post
{
    public string Id { get; set; }
    public string Title { get; set; }
    public string Content { get; set; }
}

And defined mapping using BsonClassMap:

BsonClassMap.RegisterClassMap<Domain.Entities.Post>(x =>
        {
            x.AutoMap();
            x.MapIdField(x => x.Id)
                .SetSerializer(new StringSerializer(BsonType.ObjectId))
                .SetIgnoreIfDefault(true);
        });

Here's is the code:

public async Task Create(Domain.Entities.Post entity, CancellationToken cancellationToken)
    {
        async Task Create()
        {
            await Post.InsertOneAsync(entity);
        }
        await Create();
        var e = entity;
    }

When I inspect the entity the Id property is null.

So, how do I get id when using the BsonClassMap?

over 4 years ago · Santiago Trujillo
1 answers
Answer question

0

Currently, your code knows how to read Ids when they come as ObjectId from the database but still needs help when it comes to generating ids on the client side,

The missing part is SetIdGenerator method invocation, try:

BsonClassMap.RegisterClassMap<Post>(x =>
    {
        x.AutoMap();
        x.MapIdField(x => x.Id)
            .SetIdGenerator(StringObjectIdGenerator.Instance)
            .SetSerializer(new StringSerializer(BsonType.ObjectId))
            .SetIgnoreIfDefault(true);
    });

Now ObjectIds will be generated and turned into string on the client side so you should be able to see them when you hover over e variable.

Details here.

over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!