_id field serialized as null when using an interface in dotnet mongodb driver

31 views Asked by At

I have a setup which requires me to rely on an interface to create my IMongoCollection. Basically the objects I’m persisting are using generics so I cannot use a class in GetCollection<>.

I have a custom discriminator which i register with the interface and all possible generics like this:

BsonSerializer.RegisterDiscriminatorConvention(typeof(IMyClass), new MyClassConvention());

foreach (var type in genericOptions) {
    var genType = typeof(MyClass<>).MakeGenericType(type);
    BsonSerializer.RegisterDiscriminatorConvention(genType, new MyClassConvention());
}

The object has a string Id field which i expect to be auto filled by the mongo driver. However the serializer now becomes DiscriminatedInterfaceSerializer which does not implement the interface IBsonIdProvider.

Can someone tell me what the best approach is for my setup? I would like to rely on the default serialization as the rest of my object is serialized and deserialized properly, however its just persisting the _id field as null.

I couldnt register a custom serializer as its evaluating it for the interface only. I tried adding it to the ClassMap, but its already registered after registering the DiscriminatorConvention.

When I use [BsonIgnoreIfDefault] the id field does not get serialized as null and mongodb sets the id but it is not updated in the in memory object after the InsertOne call.

0

There are 0 answers