[CSHARP-2740] The projection serializer does not respect Bson[Class]Map and custom serialization parameters Created: 10/Sep/19  Updated: 31/Mar/22

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

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


 Description   

Not sure if this is intended, but the anonymous-type based full-document projection respects the Bson[Class]Map settings, while the partial projection does not. In the following example the "Value" field of the "Data" class default is set to -1. When projecting the full document, the full serializer is used and the projected value is -1. When really proecting fields, the default (0) is used. This can bring nasty surprises because full-document projection can be used when the projection expression references document object itself, so changing the projected fields could influence the value of the other, non-projected fields.

        private class Data
        {
            [Bson.Serialization.Attributes.BsonDefaultValue(-1)]
            public int A { get; set; }
        }
 
        [Fact]
        public void Should_produce_serializer_that_respects_bson_map()
        {
            var data = ProjectData(x => x, "{}");
            data.A.Should().Be(-1);
        }
 
        [Fact]
        public void Should_produce_serializer_that_respects_bson_map_when_projecting()
        {
            var data = ProjectData(x => new { x.A }, "{}");
            data.A.Should().Be(-1);
        }
 
        private T ProjectData<T>(Expression<Func<Data, T>> projector, string json)
        {
            var serializer = BsonSerializer.SerializerRegistry.GetSerializer<Data>();
            var projectionInfo = FindProjectionTranslator.Translate<Data, T>(projector, serializer, BsonSerializer.SerializerRegistry);
 
            using (var reader = new JsonReader(json))
            {
                var context = BsonDeserializationContext.CreateRoot(reader);
                return projectionInfo.ProjectionSerializer.Deserialize(context);
            }
        }


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