Since upgrading to .NET 6 to .NET 8, we are getting very unusual and sporadic behaviour from MongoDB (driver?). Every couple of days (sometimes weeks) the driver would start throwing the following exception during data read:
System.FormatException: An error occurred while deserializing the Id property of class X : Cannot deserialize a 'String' from BsonType 'ObjectId'.
where X is a root class for 2 derived classes A & B:
public class X
{
// MongoDB ObjectId
public string Id { get; set; }
// Other common properties...
}
public class A : X
{
// Stuff... but without ID (it is inherited from X)
}
public class B : X
{
// Stuff... but without ID (it is inherited from X)
}
This exception would continue to be thrown until the app is restarted which makes it work again for a couple of days.
MongoDB.Driver version is v3.4.0, server version is v4.2.8.
- We are mapping our classes generically (no attributes whatsoever) before the connection is used.
- Class maps are registered in a static constructor.
- Documents are only inserted in an
Xcollection.AorBis queried usingOfTypeon theXcollection. - Inserted documents have the correct discriminator
_t: [ X, A (or B) ]meaning it’s an array. I followed this web guide for polymorphism in MongoDB TDocumentcan only beX. Meaning the order of class map registration isX -> A/B -> B/A.- Our Mongo wrapper is a singleton.
static MongoWrapper()
{
BsonSerializer.TryRegisterSerializer(new GuidSerializer(GuidRepresentation.CSharpLegacy));
RegisterClassMap(typeof(TDocument), "Id");
// not ideal -- I know
var derivedTypes = AppDomain.CurrentDomain.GetAssemblies()
.SelectMany(assembly => assembly.GetLoadableTypes())
.Where(type => type is not null && !type.IsAbstract && type.IsSubclassOf(typeof(TDocument)));
foreach (var derivedType in derivedTypes)
{
RegisterClassMap(derivedType, "Id");
}
ConventionRegistry.Register(
"DocumentStorage.IgnoreExtraElements",
new ConventionPack() { new IgnoreExtraElementsConvention(true) },
type => true
);
ConventionRegistry.Register(
"DocumentStorage.IgnoreNull",
new ConventionPack { new IgnoreIfNullConvention(true) },
type => true
);
}
private static void RegisterClassMap(Type classType, string idPropertyName)
{
if (classType.BaseType != typeof(object) && !BsonClassMap.IsClassMapRegistered(classType.BaseType))
RegisterClassMap(classType.BaseType, idPropertyName);
else if (classType is null || classType == typeof(object))
return;
if (!BsonClassMap.IsClassMapRegistered(classType))
{
var baseMap = BsonClassMap.IsClassMapRegistered(classType.BaseType)
? BsonClassMap.LookupClassMap(classType.BaseType)
: null;
var classMap = new BsonClassMap(classType, baseMap);
classMap.AutoMap();
classMap.SetIgnoreExtraElements(true);
if (classMap.BaseClassMap?.IdMemberMap is null)
{
classMap.SetIsRootClass(true);
classMap.MapIdProperty(idPropertyName)
.SetSerializer(new StringSerializer(BsonType.ObjectId))
.SetIdGenerator(StringObjectIdGenerator.Instance)
.SetIgnoreIfNull(false)
.SetIgnoreIfDefault(true);
}
classMap.Freeze();
BsonClassMap.RegisterClassMap(classMap);
}
}
No other class is manipulating the MongoDB and only one place is registering the class maps. The documents are stored with an ID. Even with the exceptions happening the documents are still stored with an ID.
Example of the code that pulls data:
var collection = database.GetCollection<X>("XCollection").OfType<A>();
var data = await collection.Find(<lambda>).ToListAsync()
Am totally lost,
- Has anybody faced the same issue and was able to find a solution?
- Why is ID deserialization working and after Z amount of time it breaks?
- Why is the issue only happening on .net 8?
- Is there something obvious I am missing?
Please let me know if you need more info.
- I tried: pulling data of type
Afrom collectionX - I expect: to get data of type
A - Actual result:
FormatExceptionsaying it cannot deserialize the ID property ofX(even though it worked only moments earlier)
Full exception:
System.FormatException: An error occurred while deserializing the Id property of class X: Cannot deserialize a 'String' from BsonType 'ObjectId'.
---> System.FormatException: Cannot deserialize a 'String' from BsonType 'ObjectId'.
at MongoDB.Bson.Serialization.Serializers.StringSerializer.DeserializeValue(BsonDeserializationContext context, BsonDeserializationArgs args)
at MongoDB.Bson.Serialization.BsonClassMapSerializer`1.DeserializeMemberValue(BsonDeserializationContext context, BsonMemberMap memberMap)
--- End of inner exception stack trace ---
at MongoDB.Bson.Serialization.BsonClassMapSerializer`1.DeserializeMemberValue(BsonDeserializationContext context, BsonMemberMap memberMap)
at MongoDB.Bson.Serialization.BsonClassMapSerializer`1.DeserializeClass(BsonDeserializationContext context)
at MongoDB.Bson.Serialization.BsonClassMapSerializer`1.Deserialize(BsonDeserializationContext context, BsonDeserializationArgs args)
at MongoDB.Driver.OfTypeSerializer`2.Deserialize(BsonDeserializationContext context, BsonDeserializationArgs args)
at MongoDB.Bson.Serialization.IBsonSerializerExtensions.Deserialize[TValue](IBsonSerializer`1 serializer, BsonDeserializationContext context)
at MongoDB.Driver.Core.Operations.CursorBatchDeserializationHelper.DeserializeBatch[TDocument](RawBsonArray batch, IBsonSerializer`1 documentSerializer, MessageEncoderSettings messageEncoderSettings)
at MongoDB.Driver.Core.Operations.FindOperation`1.CreateFirstCursorBatch(BsonDocument cursorDocument)
at MongoDB.Driver.Core.Operations.FindOperation`1.CreateCursor(IChannelSourceHandle channelSource, IChannelHandle channel, BsonDocument commandResult)
at MongoDB.Driver.Core.Operations.FindOperation`1.ExecuteAsync(RetryableReadContext context, CancellationToken cancellationToken)
at MongoDB.Driver.Core.Operations.FindOperation`1.ExecuteAsync(IReadBinding binding, CancellationToken cancellationToken)
at MongoDB.Driver.OperationExecutor.ExecuteReadOperationAsync[TResult](IReadBinding binding, IReadOperation`1 operation, CancellationToken cancellationToken)
at MongoDB.Driver.MongoCollectionImpl`1.ExecuteReadOperationAsync[TResult](IClientSessionHandle session, IReadOperation`1 operation, ReadPreference readPreference, CancellationToken cancellationToken)
at MongoDB.Driver.MongoCollectionImpl`1.UsingImplicitSessionAsync[TResult](Func`2 funcAsync, CancellationToken cancellationToken)
at MongoDB.Driver.IAsyncCursorSourceExtensions.ToListAsync[TDocument](IAsyncCursorSource`1 source, CancellationToken cancellationToken)
Exception.ToString()orLogger.LogError(exception,message,...). You didn't post the full exception text so we can't guess which method threw, what part of the code causes this, or even if the code is relevant. The exception means the payload isn't what you assumed. It's not sporadic, it means there's a programming or logic error.stringtype really is wrong, because MongoDB returned an ObjectID. Perhaps you can add an attribute to specify the mapping