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
?
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.