Problem mapping classes with .NET driver 2.11.0

https://mongodb.github.io/mongo-csharp-driver/2.10/reference/bson/mapping/
I follow the docs before, I found it’s works like this

public class Employee 
{
    [BsonRepresentation(BsonType.ObjectId)]
    public string Id { get; set; }
}

but it doesn’t work like this

BsonClassMap.RegisterClassMap<Employee>(cm => 
{
    cm.AutoMap();
    cm.IdMemberMap.SetSerializer(new StringSerializer(BsonType.ObjectId));
});

Hi @funk_xie,

With AutoMap() you don’t need to register ObjectId, it should already be registered by default.
Could you elaborate with examples on what are you trying to do ? For example, it would be helpful to provide:

  • What operation/process you would like to perform ?
  • What output that you would like to see after the operation ?
  • What have you tried ?
  • What output you’re getting at the moment ?

Regards,
Wan.

Hi wan,
Thanks for your reply.
I expect that the property Id will convert to string type when reading data from the database and will convert the string type back to an ObjectId type when writing data to the database.
The operation is insert a new data into database, for example, this is my class named MyClass
public class MyClass
{
public string Id { get; set; }
public string Name { get; set; }
}
this is the entity
var myClass = new MyClass{ Name = "testClass" };
when i use attribute [BsonRepresentation(BsonType.ObjectId)] it will create a new objectId automatic but when i use lambda expressions to register it won’t create new id, it will insert a null value. Must i create a new objectId value manual?

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.

1 Like

Thank U very much! :smiley: :smiley: :smiley: :smiley: :smiley:

This topic was automatically closed 5 days after the last reply. New replies are no longer allowed.