Hi @funk_xie,
You don’t need to register the BSON representation for ObjectId
. For example, you could have the following class mapping:
public class MyClass
{
[BsonRepresentation(BsonType.ObjectId)]
public string Id { get; set; }
public string Name {get; set;}
}
When you perform an insert as below. The value of Id
will be automatically filled with an ObjectId.
var document = new MyClass { Name = "Foo" };
collection.InsertOne(document);
You could also specify your own Id
(with a valid ObjectId hex string format) as below. The string value will be serialised into ObjectId
in the database.
var document2 = new MyClass {Id="5f488a68d1314f2be9ea5b7d", Name="Bar"};
collection.InsertOne(document2);
When you read the value of the Id
field, that would automatically be mapped back to string, for example:
var result = collection.Find(new BsonDocument()).FirstOrDefault();
Console.WriteLine(result.Id);
// Outputs string "5f488a68d1314f2be9ea5b7d"
Regards,
Wan.