Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 794
Adam Avatar asked Sep 10 '26 13:09

Adam


1 Answers

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

BsonSerializer.RegisterSerializer(new GuidSerializer(GuidRepresentation.Standard));
like image 170
Adam Avatar answered Sep 12 '26 04:09

Adam



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!