[CSHARP-2469] Check for TypeConverters on serialization/deserialization when no explicit serializer present Created: 04/Jan/19 Updated: 27/Oct/23 Resolved: 15/Jan/19 |
|
| Status: | Closed |
| Project: | C# Driver |
| Component/s: | None |
| Affects Version/s: | 2.7.2 |
| Fix Version/s: | None |
| Type: | Improvement | Priority: | Major - P3 |
| Reporter: | Brian Buvinghausen | Assignee: | Robert Stam |
| Resolution: | Works as Designed | Votes: | 0 |
| Labels: | None | ||
| Remaining Estimate: | Not Specified | ||
| Time Spent: | Not Specified | ||
| Original Estimate: | Not Specified | ||
| Environment: |
All: .NET Core - Windows, Linux, & OSX |
||
| Description |
|
Currently it seems like the MongoDB C# driver doesn't support any aspect of the notions of .NET TypeConverters If a type has a TypeConverter configured and can serialize to and from strings it makes a whole heck of a lot of sense to simply use the type converter out of the box to perform the conversions. This is what JSON.NET does and it is "especially" true when using a type like this as a key in a dictionary which implicitly has to be a string. When I feed a dictionary keyed by a type with a type converter I get this error in the driver... MongoDB.Bson.BsonSerializationException If you just leverage the configured type converter it will yield back the string and you can continue on your merry way rather than me having to set explicit mongo specific serializers for each type which is a pain. |
| Comments |
| Comment by Robert Stam [ 15/Jan/19 ] | ||||||||||
|
We think it is dangerous to do too many automatic conversions because the risk of undesirable results is too high. Consider your scenario requesting that keys of a dictionary be automatically converted to strings if necessary. The following dictionary would somewhat surprisingly result in duplicate element names:
As another example of undesirable conversions, consider an example of a hypothetical class X that does not override ToString:
In .NET when a class does not override ToString the default implementation of ToString is to return the class name, which in this example would result in duplicate elements named something like "TestProgram.X" if keys were automatically converted to strings. Consider also whether you would be willing for conversions to result in inaccurate round trips of data saved to the database. For example, if the integer 42 is converted to the string "42" when saving the document, then when the document is read back the key in the dictionary would now be the string "42" rather than the original key which was an integer 42. Have you considered using alternate DictionaryRepresentations like ArrayOfArrays or ArrayOfDocuments? These representations don't require that the keys be strings. In summary, we think it is safer to require the application to explicitly configure any conversions it wishes to have happen. |