-
Type:
Improvement
-
Resolution: Unresolved
-
Priority:
Minor - P4
-
None
-
Affects Version/s: 3.5.0
-
Component/s: Serialization
As reported in this StackOverflow question: MongoDB.Bson.BsonSerializationException after C# driver update to 3.5.0(https://stackoverflow.com/q/79780239/8017690),
I believe this bug happened after the introduction of [Serialization ignores discriminator field when checking for duplicate field names](http://jira.mongodb.org/browse/CSHARP-4040).
Here is how the Post owner code looks:
public record IdentifierSheet
{
public required string Identifier
public Security SecurityType { get; init; }
public required string Symbol { get; init; }
public Exchange Exchange { get; init; }
public string? Name { get; init; }
}
public record FutureIdentifierSheet : IdentifierSheet
{
public string Underlying { get; init; }
= string.Empty;
public required DateTime ExpirationDate { get; init; }
public required string ProductCode { get; init; }
public required DateTime YearMonth { get; init; }
}
private class SecurityTypeDiscriminatorConvention : IDiscriminatorConvention
{
public string ElementName => nameof(IdentifierSheet.SecurityType);
public Type GetActualType(IBsonReader bsonReader, Type nominalType)
{
var bookmark = bsonReader.GetBookmark();
bsonReader.ReadStartDocument();
var actualType = typeof(IdentifierSheet);
while (bsonReader.ReadBsonType() != BsonType.EndOfDocument)
{
string? name = bsonReader.ReadName();
if (name == ElementName)
{
var enumValue = (SecurityType.Security)(object)bsonReader.ReadInt32();
actualType = enumValue switch
;
break;
}
bsonReader.SkipValue();
}
bsonReader.ReturnToBookmark(bookmark);
return actualType;
}
public BsonValue GetDiscriminator(Type nominalType, Type actualType)
{
if (actualType == typeof(FutureIdentifierSheet))
return (int)SecurityType.Security.Future;
if (actualType == typeof(OptionIdentifierSheet))
return (int)SecurityType.Security.Option;
return (int)SecurityType.Security.NoSecurity; // fallback or base
}
}
My question is:
- Is it still possible to have the discriminator as a property in the class?
- If yes, please provide the workaround example to achieve.
Thanks.
- depends on
-
CSHARP-4040 Serialization ignores discriminator field when checking for duplicate field names
-
- Closed
-
- is related to
-
CSHARP-5747 3.5.0 Discriminator breaking changes (Cannot map "_t" to Class Property any more)
-
- Closed
-