0

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 X collection. A or B is queried using OfType on the X collection.
  • 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
  • TDocument can only be X. Meaning the order of class map registration is X -> 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 A from collection X
  • I expect: to get data of type A
  • Actual result: FormatException saying it cannot deserialize the ID property of X (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)
12
  • Post the full exception text - whatever is returned by Exception.ToString() or Logger.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. Commented Jul 14 at 8:06
  • @PanagiotisKanavos updated
    – bgajic
    Commented Jul 14 at 8:09
  • 1
    There are several questions about this exact error, like this one, this one and at least 13 others. Have you checked them? Perhaps the string type really is wrong, because MongoDB returned an ObjectID. Perhaps you can add an attribute to specify the mapping Commented Jul 14 at 8:16
  • 2
    Does that mean the documents that throw are always the same? That's the opposite of sporadic. Have you tried adding the attribute? You can argue about how things should work, or you can try to narrow down the actual behavior and the problem to specific or random documents, specific configurations. Besides, the exception isn't thrown by .NET 8, it's thrown by the MongoDB driver. It's quite possible it became stricter. If you upgraded from 2.x to 3.0, there will be breaking changes. GUID serialization certainly changed in 3.0.0 Commented Jul 14 at 8:31
  • 3
    Try creating unit tests that work with the problematic documents. Try creating both .NET 6 and .NET 8 test projects, using old and new driver versions, to isolate which version introduced the problem. If .NET 6 with an old driver still has problems, the problem is almost certainly the document Commented Jul 14 at 8:33

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.