Skip to content

Commit fad2887

Browse files
committed
CSHARP-2643: Automapped serializer for anonymous classes should use default values for missing elements when deserializing.
1 parent ef33873 commit fad2887

File tree

2 files changed

+57
-1
lines changed

2 files changed

+57
-1
lines changed

src/MongoDB.Bson/Serialization/Conventions/ImmutableTypeClassMapConvention.cs

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -76,7 +76,12 @@ public void Apply(BsonClassMap classMap)
7676
// if any constructors were mapped by this convention then map all the properties also
7777
foreach (var property in properties)
7878
{
79-
classMap.MapMember(property);
79+
var memberMap = classMap.MapMember(property);
80+
if (classMap.IsAnonymous)
81+
{
82+
var defaultValue = memberMap.DefaultValue;
83+
memberMap.SetDefaultValue(defaultValue);
84+
}
8085
}
8186
}
8287
}
Lines changed: 51 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,51 @@
1+
/* Copyright 2019-present MongoDB Inc.
2+
*
3+
* Licensed under the Apache License, Version 2.0 (the "License");
4+
* you may not use this file except in compliance with the License.
5+
* You may obtain a copy of the License at
6+
*
7+
* http://www.apache.org/licenses/LICENSE-2.0
8+
*
9+
* Unless required by applicable law or agreed to in writing, software
10+
* distributed under the License is distributed on an "AS IS" BASIS,
11+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12+
* See the License for the specific language governing permissions and
13+
* limitations under the License.
14+
*/
15+
16+
using FluentAssertions;
17+
using MongoDB.Bson.IO;
18+
using MongoDB.Bson.Serialization;
19+
using Xunit;
20+
21+
namespace MongoDB.Bson.Tests.Jira
22+
{
23+
public class CSharp2643Tests
24+
{
25+
[Theory]
26+
[InlineData("{ }", 0, 0)]
27+
[InlineData("{ X : 1 }", 1, 0)]
28+
[InlineData("{ Y : 2 }", 0, 2)]
29+
[InlineData("{ X : 1, Y : 2 }", 1, 2)]
30+
public void Deserializer_should_return_expected_result(string json, int expectedX, int expectedY)
31+
{
32+
var prototype = new { CSharp2643 = true, X = 1, Y = 2 }; // use CSharp2643 as a property name to guarantee a unique anonymous type
33+
34+
T deserialize<T>(T dummy, string value)
35+
{
36+
var serializer = BsonSerializer.LookupSerializer<T>();
37+
using (var reader = new JsonReader(value))
38+
{
39+
var context = BsonDeserializationContext.CreateRoot(reader);
40+
return serializer.Deserialize(context);
41+
}
42+
}
43+
44+
var result = deserialize(prototype, json);
45+
46+
result.CSharp2643.Should().BeFalse();
47+
result.X.Should().Be(expectedX);
48+
result.Y.Should().Be(expectedY);
49+
}
50+
}
51+
}

0 commit comments

Comments
 (0)