Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

274
Views
Unknown discriminator value MongoDB

I basically want a collection that saves multiple types of objects/documents but all of them inherit from a base interface.. However, I am keep getting this exception when loading:

Additional information: An error occurred while deserializing the Inventory property of class Character: Unknown discriminator value 'TestItem'.

Here is my codes:

public class Character
{
    ...
    public List<IInventoryItem> Inventory { get; set; }
    ...
}

public interface IInventoryItem
{
...
}

class TestItem : IInventoryItem
{
...
}

Help is very appreciated.

about 4 years ago · Santiago Trujillo
1 answers
Answer question

0

The problem is that you don't explicitly declare your polymorphic types to MongoDB driver.

For that, you have two options: using attributes, or a mapping configuration method. More info here: http://mongodb.github.io/mongo-csharp-driver/2.2/reference/bson/mapping/

Using attributes:

[BsonDiscriminator("TestItem")]
public class TestItem : IInventoryItem
{
    ...
} 

Using mapping configuration method:

BsonClassMap.RegisterClassMap<TestItem>(); // do it before you access DB

WHY: documents that represent polymorphic types (e.g. interfaces) are saved to the DB with a special field named _t, which contains discriminator value. In your case, the Character document will look like this:

{
    // ... other fields
    Inventory: [
        {
            _t: "TestItem",
            //... other fields
        }, 
        {
            _t: "TestItem",
            //... other fields
        }
    ]
    // ... other fields
}

On write, if the mappings don't exist, they are created on the fly, and TestItem discriminator is mapped to TestItem class. From that moment on, the mappings exist for the life of the AppDomain. Thus for example, if you perform reads after writes, it will be OK.

But if you read data first thing, BSON serializer doesn't know what type the TestItem discriminator maps to. So it is good practice to always explicitly specify discriminator mappings. In this way you can also control discriminator values - by default they equal to type name.

about 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!