-
Type:
Bug
-
Resolution: Unresolved
-
Priority:
Unknown
-
None
-
Affects Version/s: 3.4.0
-
Component/s: Serialization
-
None
According to the docs BsonSerializer.RegisterDiscriminator should "register a discriminator for a type". This is not true though, as the following failing test demonstrates:
BsonSerializer.RegisterDiscriminator(typeof(DerivedPerson), "TestDiscriminator"); var collection = db.GetCollection<BasePerson>(DriverTestConfiguration.CollectionNamespace.CollectionName); var bsonCollection = db.GetCollection<BsonDocument>(DriverTestConfiguration.CollectionNamespace.CollectionName); var person = new DerivedPerson { Id = ObjectId.Parse("6797b56bf5495bf53aa3078f"), Name = "Mario", Age = 24 }; collection.InsertOne(person); var retrieved = bsonCollection.FindSync("{}").ToList().Single(); var toString = retrieved.ToString(); var expectedVal = """{ "_id" : { "$oid" : "6797b56bf5495bf53aa3078f" }, "_t" : "TestDiscriminator", "Name" : "Mario", "Age" : 24 }"""; Assert.Equal(expectedVal, toString);
The correct current way (as reported in our online documentation) is to register the discriminator when creating the class map, or using attributes. The reason why the method does not work, is that the "discriminator dictionary" that it created is not used when looking for the discriminator, but that is found directly on the class map.
It seems that the discriminator dictionary is used only when making queries, and is populated when the class map are registered.
I would suggest to remove this method from the public API and make it internal.