将IList <guid>作为BsonString而不是LUUID

时间:2019-05-08 13:26:20

标签: c# .net mongodb asp.net-core .net-core

我在MongoDb中存储的Guid列表有问题。我想将它们存储为字符串而不是LUUID条目。

当前,我正在使用BsonRepresentation(BsonType.String)属性表示法,但我想将其替换为初始化代码,以便将所有内容都放在一个位置。

using System;
using System.Collections.Generic;
using MongoDB.Bson;
using MongoDB.Bson.Serialization.Attributes;

namespace Program.Dto
{
    public class Node
    {
        public Guid Id { get; set; }
        public string Name { get; set; }
        public IList<Node> Groups { get; set; }
        [BsonRepresentation(BsonType.String)]
        public IList<Guid> Classes { get; set; }
        public static Node Create(string name)
        {
            return new Node
            {
                Id = Guid.NewGuid(),
                Name = name,
                Groups = new List<Node>(),
                Classes = new List<Guid>()
            };
        }
    }
}

这是我的初始化代码:

BsonClassMap.RegisterClassMap<Node>(cm =>
{
    cm.AutoMap();
    cm.SetIdMember(cm.GetMemberMap(c => c.Id));
    cm.GetMemberMap(c => c.Classes).SetSerializer(new GuidSerializer().WithRepresentation(BsonType.String));
});

但是显然我遇到了错误,因为它是一个列表,而不是Guid本身。

System.ArgumentException: 'Value type of serializer is System.Guid  and does not match member type System.Collections.Generic.IList`1[[System.Guid, System.Private.CoreLib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e]].'

所以,我可能需要一个自定义的序列化程序,并附带以下内容:

using System;
using System.Collections.Generic;
using MongoDB.Bson;
using MongoDB.Bson.Serialization;

namespace Program.MongoDB.BsonSerializers
{
    public sealed class GuidListSerializer : BsonSerializerBase<IList<Guid>>
    {
        public override IList<Guid> Deserialize(BsonDeserializationContext context, BsonDeserializationArgs args)
        {
            var guids = new List<Guid>();

            var bsonReader = context.Reader;
            bsonReader.ReadStartDocument();
            bsonReader.ReadString();
            bsonReader.ReadStartArray();

            while (bsonReader.ReadBsonType() != BsonType.EndOfDocument)
            {
                var guid = new Guid(bsonReader.ReadBinaryData().Bytes);
                guids.Add(guid);
                bsonReader.ReadEndArray();
            }

            bsonReader.ReadEndDocument();

            return guids.AsReadOnly();
        }

//Override the serialize method for storing guids as strings?

    }
}

但是我在bsonReader.ReadEndArray()上遇到错误,并且MongoDb中的条目存储为LUUID而不是String。

System.InvalidOperationException: 'ReadEndArray can only be called when State is EndOfArray, not when State is Value.'

我希望能够将Guids存储为字符串而不使用属性。

[BsonRepresentation(BsonType.String)]

1 个答案:

答案 0 :(得分:1)

您应该检查读取器的状态,并且仅在状态合适时才读取数组的结尾:

while (bsonReader.State != BsonReaderState.EndOfArray)
{
    var guid = new Guid(bsonReader.ReadBinaryData().Bytes);
    guids.Add(guid);
}

bsonReader.ReadEndArray();