[CSHARP-2458] Inserting an array into a child collection in MongoDB is omitting the _t Discriminator Created: 18/Dec/18  Updated: 31/Mar/22

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

Type: Bug Priority: Major - P3
Reporter: yonatan ben avraham Assignee: Unassigned
Resolution: Unresolved Votes: 0
Labels: None
Remaining Estimate: Not Specified
Time Spent: Not Specified
Original Estimate: Not Specified

Issue Links:
Duplicate

 Description   

When using the insertOne function in the C# driver, in case we initialize an array with {{new[]

{obj, obj, obj}

}}.  The _t Discriminator is missing in the DB.

 

for example:

collection.InsertOne(new Parent { Children = new[] { new Child() } });

will save to DB:

{"_id":"5bf6aef6c0beccc414b70d45","Child":[{}]}

The problem does not happen when using List

collection.InsertOne(new Parent { Children = new List<IChild> { new Child() } });

will insert into DB:

{    "_id":"5bf6b074c0beccc414b70dc2",    "Children":[{"_t":"Child"}]}

for further information please check this StackOverflow question:

https://stackoverflow.com/questions/53432370/inserting-an-array-into-a-child-collection-in-mongodb-is-omitting-the-t-discrim/53544804?noredirect=1#comment94153188_53544804



 Comments   
Comment by Wan Bachtiar [ 15/Jan/19 ]

Hi yonbav,

Thanks for the bug report. I'm able to reproduce this behaviour (MongoDB .NET/C# v2.7.2). The following example will store in MongoDB without _t discriminator:

class Program
    {
        public class Parent 
        {
            public IEnumerable<IChild> Children {get; set;}
        }        
        public interface IChild {}
        public class Child: IChild {}
        static void Main(string[] args)
        {
            var mongoURL = new MongoUrl("mongodb://<host>:<port>");
            var client = new MongoClient(mongoURL);
            var database = client.GetDatabase("databaseName");            
            var collection = database.GetCollection<Parent>("collectionName");
            var document = new Parent { Children = new [] { new Child () }};
            collection.InsertOne(document);
        }
    }

This is a bug in the serialisation of individual items in the Children collection, where the driver is using the incorrect NomicalType for the items.

In the meantime, there are 2 workarounds that you could use, explicitly specify that the class requires a discriminator:

        [BsonDiscriminator(Required=true)]
        public class Child: IChild {}

Or, explicitly specify the type of the array:

 var document = new Parent { Children = new IChild[] { new Child() }};

Regards,
Wan.

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