A good solution consists in letting the client generate the _id
for you.
public class MyEntity
{
[BsonId(IdGenerator = typeof(ObjectIdGenerator))]
public ObjectId Id { get; set; }
public string SomeStringProperty { get; set; }
public DateTime SomeDateTimeProperty { get; set; }
}
The _id
is generated whenever an entity with null _id
is inserted in the database, and it's up to the driver to provide an _id
value before insertion.
In case you don't want to reference MongoDB library in your domain model (so as I prefer) you might simply define your entity as follows.
public class MyEntity
{
public string Id { get; set; }
public string SomeStringProperty { get; set; }
public DateTime SomeDateTimeProperty { get; set; }
}
Then, use this code directly in the persistence layer to map your entity with the database.
BsonClassMap.RegisterClassMap<MyEntity>(cm =>
{
cm.AutoMap();
cm.MapIdMember(c => c.Id)
.SetIdGenerator(StringObjectIdGenerator.Instance)
.SetSerializer(new StringSerializer(BsonType.ObjectId));
});
string
Ids are easier to be handled in the code, though this way they are mapped as ObjectId
within the database.
Be careful: if you use the async version of InsertOne()
method, you must wait for the insert to be at least started before getting the _id
value set by the driver.