简体   繁体   中英

MongoDB C# does not generate a value for _id/ObjectId when using StringObjectIdGenerator

I am trying to follow the example here , but something is not working right. I've implemented the following:

My Model

public class MyModel { 
       public string MyModelId { get; set; } 
       //Other properties 
 }

My mapping

    BsonClassMap.RegisterClassMap<MyModel>(cm =>
        {
            cm.AutoMap();
            cm.MapIdProperty(c => c.MyModelId)
                    .SetIdGenerator(StringObjectIdGenerator.Instance)
                    .SetSerializer(new StringSerializer(BsonType.ObjectId));

        });

My Insert

        if (!BsonClassMap.IsClassMapRegistered(typeof(MyModel)))
        {
            //Do the mapping above
        }

        var collection = RetrieveCollection("MyModels"); //method used to retrieve an IMongoCollection from the database.
        var bsonDoc = model.ToBsonDocument(); //model is an argument passed in to the method of type MyModel

        collection.InsertOne(bsonDoc);

Every time it gets done doing the InsertOne() operation, there is no element in the BsonDocument for MyModelId. Furthermore, there is an element for _id in the BsonDocument that is always set to "BsonNull". Then if I try to insert again, MongoDB throws a " E11000 duplicate key error collection:" error, presumably because one already exists with a value of "BsonNull".

If I comment out my mapping, an ObjectId value gets created for _id, but then I cannot deserialize back to MyModel.

Why doesn't the StringObjectIdGenerator actually generate an ID?

Alright, with the some educated guessing after view This post , I tried the following:

    BsonClassMap.RegisterClassMap<MyModel>(cm =>
    {
        cm.AutoMap();
        cm.MapIdProperty(c => c.MyModelId)
                .SetIgnoreIfDefault(true) //added this line
                .SetIdGenerator(StringObjectIdGenerator.Instance)
                .SetSerializer(new StringSerializer(BsonType.ObjectId));

    });

This seems to have resolved the issue. When inserting the BsonDocument, I still saw the "_id" field, instead of "MyModelId". However the "_id" field had a value in it. Furthermore when I retrieved the value from the collection, and deserialized it back to a MyModel object the MyModelId property was populated by the value previously saw in "_id".

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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