'C# MongoDB Guid Array

I have a document that is represented using this class

public class UnitDocument
{
    [BsonConstructor]
    public UnitDocument(Guid id, string allocId, Guid[] attachments)
    {
        Id = id;
        AllocId = allocId;
        Attachments = attachments;
    }

    [BsonId, BsonGuidRepresentation(GuidRepresentation.Standard)]
    public Guid Id { get; }

    [BsonElement]
    public string AllocId { get; }
    
    [BsonElement]
    public Guid[] Attachments { get; }
}

When I try to use the C# driver to insert a document I get the following error:

MongoDB.Bson.BsonSerializationException: GuidSerializer cannot serialize a Guid when GuidRepresentation is Unspecified.

I tried setting the GuidRepresentation doing the following:

[BsonElement, BsonGuidRepresentation(GuidRepresentation.Standard)]
public Guid[] Attachments { get; }

After doing this I get

System.InvalidOperationException: [BsonGuidRepresentationAttribute] can only be used when the serializer is a GuidSerializer.

So I thought, I will set the Serializer:

[BsonElement, BsonGuidRepresentation(GuidRepresentation.Standard), BsonSerializer(typeof(GuidSerializer))]
public Guid[] Attachments { get; }

Which then leads to:

System.ArgumentException: Value type of serializer is System.Guid and does not match member type System.Guid[]. (Parameter 'serializer')

What am I missing here?

Also note, that I have set the following settings globally, on startup:

BsonDefaults.GuidRepresentationMode = GuidRepresentationMode.V3;

An alternative that works, but I am not super keen on is this

[BsonElement, BsonRepresentation(BsonType.String)]
public Guid[] Attachments { get; }

Is there no way to store Guids in an array in MongoDB?



Solution 1:[1]

Adding the following line to the start-up code fixed the issue.

BsonSerializer.RegisterSerializer(new GuidSerializer(GuidRepresentation.Standard));

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Adam