File tree Expand file tree Collapse file tree
src/MongoDB.Bson/Serialization
tests/MongoDB.Bson.Tests/Serialization Expand file tree Collapse file tree Original file line number Diff line number Diff line change @@ -1325,12 +1325,14 @@ internal IDiscriminatorConvention GetDiscriminatorConvention()
13251325 {
13261326 // it's possible but harmless for multiple threads to do the discriminator convention lookup at the same time
13271327 discriminatorConvention = LookupDiscriminatorConvention ( ) ;
1328- _discriminatorConvention = discriminatorConvention ;
13291328
13301329 if ( discriminatorConvention != null )
13311330 {
13321331 EnsureNoMemberMapConflicts ( discriminatorConvention . ElementName ) ;
13331332 }
1333+
1334+ // only cache if validation succeeds
1335+ _discriminatorConvention = discriminatorConvention ;
13341336 }
13351337
13361338 return discriminatorConvention ;
Original file line number Diff line number Diff line change 2222using MongoDB . Bson . IO ;
2323using MongoDB . Bson . Serialization ;
2424using MongoDB . Bson . Serialization . Attributes ;
25+ using MongoDB . Bson . Serialization . Conventions ;
2526using MongoDB . Bson . TestHelpers ;
2627using Xunit ;
2728
@@ -735,4 +736,33 @@ private class D : C
735736 {
736737 }
737738 }
739+
740+ public class BsonClassMapGetDiscriminatorConventionTests
741+ {
742+ [ Fact ]
743+ public void GetDiscriminatorConvention_should_throw_consistently_when_member_conflicts_with_discriminator_element_name ( )
744+ {
745+ BsonSerializer . RegisterDiscriminatorConvention ( typeof ( Foo ) , new FooDiscriminatorConvention5816 ( ) ) ;
746+
747+ var classMap = new BsonClassMap < Foo > ( ) ;
748+ classMap . AutoMap ( ) ;
749+ classMap . Freeze ( ) ;
750+
751+ Assert . Throws < BsonSerializationException > ( ( ) => classMap . GetDiscriminatorConvention ( ) ) ;
752+ Assert . Throws < BsonSerializationException > ( ( ) => classMap . GetDiscriminatorConvention ( ) ) ;
753+ }
754+
755+ private class Foo
756+ {
757+ [ BsonElement ( "type" ) ]
758+ public string Type { get ; set ; }
759+ }
760+
761+ private class FooDiscriminatorConvention5816 : IDiscriminatorConvention
762+ {
763+ public string ElementName => "type" ;
764+ public Type GetActualType ( IBsonReader bsonReader , Type nominalType ) => nominalType ;
765+ public BsonValue GetDiscriminator ( Type nominalType , Type actualType ) => nominalType . Name ;
766+ }
767+ }
738768}
You can’t perform that action at this time.
0 commit comments