Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

275
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda