Search code examples
c#mongodbmongodb-.net-driver

BsonDiscriminator attribute is not working ? (RegisterClassMap does)


I'm trying to serialize a simple JSON string to a BsonDocument :

var st = @"{ ""_t"" : ""Class2"", ""aaa"" : 2 }";
var bsonDocument2 = BsonSerializer.Deserialize<object>(st);
Console.WriteLine(bsonDocument2);

Where Class2 is inherited from Class1 :

[BsonKnownTypes(typeof(Class2))]
[BsonDiscriminator(Required = true)]
public class Class1

{

}
[BsonDiscriminator("Class2")]
public class Class2 : Class1
{
    [BsonElement("aaa")]
    [BsonRepresentation(BsonType.Int32)]
    public int AAA { get; set; }
}

Please notice that I do use [BsonDiscriminator("Class2")] and still I get an error :

Unknown discriminator value 'Class2'.

However, If I use BsonClassMap.RegisterClassMap<Class2>(); , I get NO exception and it all works

But I don't want to use code, but an attribute.

Question:

Why do I get an exception when using attributes?

The docs states that it is viable


Solution

  • BsonKnownTypes attribute makes the difference here. Please note that below like of code works with no exception:

    var bsonDocument2 = BsonSerializer.Deserialize<Class1>(st);
    

    Why? Because you added BsonKnownTypes to Class1 but you couldn't do that for System.Object. Moreover when you hover bsonDocument2 it will be of type Class2 which means that _t works as expected.

    Why BsonClassMap.RegisterClassMap<Class2>(); works fine ? Because it registers Class2 as a known type for all of its parent classes including object (github)