简体   繁体   English

使用BsonClassMap时获取MongoDB中插入文档的_id?

[英]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?在有人将此问题标记为MongoDB 中插入文档的 Get _id 的副本之前? please read the whole question.请阅读整个问题。

I am developing a ASP.NET Core API app with MongoDB driver.我正在使用 MongoDB 驱动程序开发 ASP.NET Core API 应用程序。

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.我面临的问题是,在数据库中插入文档后, Post class 的Id属性未分配由 MongoDB 生成的 id。

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.我发现他们使用 class 中的注释/属性解决了一些问题,但是,我正在开发一种模式,其中域类没有任何持久性知识。

I have created the entity class without annotations:我创建了没有注释的实体 class :

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

And defined mapping using BsonClassMap :并使用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.当我检查实体时,Id 属性是 null。

So, how do I get id when using the BsonClassMap ?那么,使用BsonClassMap时如何获取 id ?

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,目前,您的代码知道如何从数据库中以ObjectId形式读取 Id,但在客户端生成 id 时仍需要帮助,

The missing part is SetIdGenerator method invocation, try:缺少的部分是SetIdGenerator方法调用,试试:

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.现在 ObjectIds 将在客户端生成并转换为字符串,因此当您通过e变量进行 hover 时,您应该能够看到它们。

Details here .详情在这里

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM