例hereを実行しようとしていますが、何かが正しく動作しません。私は次のように実装しました:MongoDB C#ではStringObjectIdGeneratorを使用しているときに_id/ObjectIdの値を生成しません
マイモデル
public class MyModel {
public string MyModelId { get; set; }
//Other properties
}
私のマッピングを
BsonClassMap.RegisterClassMap<MyModel>(cm =>
{
cm.AutoMap();
cm.MapIdProperty(c => c.MyModelId)
.SetIdGenerator(StringObjectIdGenerator.Instance)
.SetSerializer(new StringSerializer(BsonType.ObjectId));
});
マイ挿入
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);
たびに、それはInsertOne()操作をやって終わっます、 MyModelIdのBsonDocumentには要素がありません。さらに、BsonDocumentには常に "BsonNull"に設定されている_idの要素があります。次に、再度挿入しようとすると、おそらく "BsonNull"の値が存在するため、MongoDBは "E11000重複キーエラーコレクション:"エラーを投げます。
マッピングをコメントアウトすると、_idのObjectId値が作成されますが、逆に逆シリアル化してMyModelに戻すことはできません。
StringObjectIdGeneratorが実際にIDを生成しないのはなぜですか?