Revious
Revious

Reputation: 8156

MongoDB Unknown discriminator value => deserialize to JSonDocument

In MongoDB I've a class with a property MyProperty of type object.

public MyClass
{
    public object MyProperty;
    public string Prop1;
    public DateTime Prop2;
    public int Prop3;
}

Serialization to MongoDB works without any problem creating a JSon of this type:

MyProperty" : {
                "_t" : "ExampleClass",
            [...]
}

But when I try do seserialize it I get the following error:

An error occurred while deserializing the MyProperty property of class MyClass: Unknown discriminator value 'ExampleClass'.

I'd like to deserialize MyProperty to a simple generic BsonDocument or to a string.

Upvotes: 3

Views: 6256

Answers (1)

geohnH
geohnH

Reputation: 522

The _t stores your custom class name. You will need to register this custom class mapping in order for mongo to know which object to use when deserializing. Here is a code example (should only need to call this once at the beginning of your application):

if (!BsonClassMap.IsClassMapRegistered(typeof(ExampleClass)))
{
   BsonClassMap.RegisterClassMap<ExampleClass>();
}

Upvotes: 6

Related Questions