Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

336
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda