Why is a type discriminator needed in the DB when the .NET runtime can determine the type needed?

39 Views Asked by At

Referring to this:

https://www.mongodb.com/docs/drivers/csharp/current/fundamentals/serialization/polymorphic-objects/#use-discriminators

If my classes are properly annotated (or mapped), why does the type discriminator need to be written out to the database (the "_t" value)? Doesn't the runtime have enough information to do serdes correctly? Do the drivers for other document DBs do this?

Having "_t" in the database seems unnecessary in terms of data topology if it's strictly used for a specific application's runtime. It's also unnecessary in terms of storage/query costs.

1

There are 1 best solutions below

0
Progman On

The discriminator field is needed in case there are multiple different types stored in the MongoDB. The .NET/C# driver alone cannot know the resulting type when deserializing, specially with inheritance involved. When you want all Animal instances from the database and send a request like that, then the return values shouldn't be "just" Animal instances. Instead the instances should be from classes like Dog, Lion or Tiger (which ultimately extends from Animal). Without the discriminator, you don't know if the animal stored was/is a dog, lion or tiger. Also, when you want to filter rows and select only Lion instances, then you need the discriminator field as well, since you need to know, which rows are lions and which rows are not.

You could argue that the combination of value fields from the model classes alone can be used to uniquely identify a specific type. However, there can be cases (depending on the model classes of course), that the value fields alone are not enough to identify the class type. As an example, the value {"Name": "Foobar"} could be an Employee, Product or Group.