我想在MongoDB中序列化,成员Engines(枚举的HashSet)作为字符串,将名称视为字符串,而不是数字 课程是:
public class EnginesPerFile
{
public Guid FileId { get; set; }
public string Path { get; set; }
public HashSet<EngineType> Engines { get; set; }
}
我想这样映射:
BsonClassMap.RegisterClassMap<EnginesPerFile>(cm =>
{
cm.AutoMap();
cm.MapIdField(c => c.FileId);
cm.MapMember(c => c.Engines).SetSerializer(new EnumSerializer<EngineType>(BsonType.String));
});
但是我收到了一个错误:
Value type of serializer is EngineType and does not match member type System.Collections.Generic.HashSet`1[[Playground.Model.EngineType, Model, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null]].
参数名称:serializer。
如何在MongoDB中序列化枚举的hashset?
答案 0 :(得分:0)
我通过编写自定义Serializer来修复它:( EngineType可以是通用T)
public class MyHashSetSerializer : SerializerBase<HashSet<EngineType>>
{
private readonly IBsonSerializer _serializer =
BsonSerializer.LookupSerializer(typeof(EngineType));
public override void Serialize(BsonSerializationContext context, BsonSerializationArgs args, HashSet<EngineType> value)
{
var set = (HashSet<EngineType>)value;
context.Writer.WriteStartDocument();
int i = 0;
foreach (var element in set)
{
context.Writer.WriteName($"[{i}]");
context.Writer.WriteString(element.ToString());
}
context.Writer.WriteEndDocument();
}
public override HashSet<EngineType> Deserialize(BsonDeserializationContext context, BsonDeserializationArgs args)
{
var set = new HashSet<EngineType>();
context.Reader.ReadStartDocument();
while (context.Reader.ReadBsonType() != 0)
{
context.Reader.SkipName();
var element =
(EngineType)_serializer.Deserialize(context, args);
set.Add(element);
}
context.Reader.ReadEndDocument();
return set;
}
}
然后我像这样注册类地图:
BsonClassMap.RegisterClassMap<EnginesPerFile>(cm =>
{
cm.AutoMap();
cm.MapIdField(c => c.FileId);
cm.MapMember(c => c.Engines).SetSerializer(new MyHashSetSerializer());
});