Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

338
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda