[CSHARP-2035] BsonExtraElements Dictionary<string, Object> fails serialization for complex types Created: 07/Sep/17  Updated: 31/Mar/22

Status: Backlog
Project: C# Driver
Component/s: Serialization
Affects Version/s: 2.4.4
Fix Version/s: None

Type: Improvement Priority: Minor - P4
Reporter: B. De Rijcke Assignee: Unassigned
Resolution: Unresolved Votes: 0
Labels: driver
Remaining Estimate: Not Specified
Time Spent: Not Specified
Original Estimate: Not Specified
Environment:

Win10 VisualStudio 2017



 Description   

Having the following situation:

public class Article
{
    [BsonId]
    [BsonRepresentation(BsonType.ObjectId)]
    public string Id { get; set; }
 
    [BsonExtraElements()]
    public Dictionary<string, Object> OtherData { get; set; }
}

It appears the the [BsonExtraElements] tag prevents the driver from serializing complex types. An example would be the following class:

public class Bird
{
    [BsonElement("_n")]
    [BsonRequired]
    public string Name { get; set; }
    [BsonElement("_s")]
    [BsonRequired]
    public string Species { get; set; }
    [BsonElement("_a")]
    [BsonRequired]
    public int Age { get; set; }
}

With this tag placed on the dictionary, the driver fails to serialize an Article, if it's dictionary contains a Brid, for example. Is this intended behavior?

Without the tag it produces:

{
    "_id" : ObjectId("59b011975b8c05376c319f01"),
    "OtherData" : {
        "testBird" : {
            "_t" : "My.NameSpace.Bird",
            "_n" : "Jerry",
            "_s" : "European starling",
            "_a" : 4
        }
    }
}

I would assume it would be possible with the tag to serialize this as:

{
    "_id" : ObjectId("59b00cdd2b6e923b50fec052")
    "Bird" : {
        "_t"  : "My.NameSpace.Bird"
        "_n" : "Jerry",
        "_s" : "European starling",
        "_a" : 4
    }
}

So that later this could be deserialized back into the 'OtherData' dictionary with the correct type. So the question I'd like to ask if I'm doing something wrong? Or is it a bug? Or is it intended behavior?

Greetings,



 Comments   
Comment by B. De Rijcke [ 07/Sep/17 ]

I see, thank you for your time. I hope this makes it into a future release!

Comment by Robert Stam [ 07/Sep/17 ]

I can reproduce this.

It's not really intended behavior. We currently assume that all the values in the BsonExtraElements dictionary are either instances of BsonValue or trivially convertible to BsonValue. We should be able to convert more complex values like your Bird class by using a serializer.

We will consider supporting this in a future release.

Generated at Wed Feb 07 21:41:26 UTC 2024 using Jira 9.7.1#970001-sha1:2222b88b221c4928ef0de3161136cc90c8356a66.