我正在重构一个代码,该代码从MongoDb集合中检索文档作为BsonDocument
。由于C#为我们提供了使用强类型类使代码更安全的可能性,所以我想创建类来表示保存在集合中的文档。
我遇到的问题是,应将属性另存为文档中的属性,有时会另存为空字符串。因此,当MongoDbDriver尝试对其进行反序列化时,抛出一个异常,表明它是嵌套文档而不是字符串。
在那种情况下,我想将属性值设置为null
。
所以我尝试在解串器上实现我的解决方案:
我的班级:
[BsonIgnoreExtraElements]
public class ExampleModel
{
[BsonId]
[BsonRepresentation(BsonType.ObjectId)]
public ObjectId Id { get; set; }
.
.
.
[BsonElement("usedTemplate")]
[BsonSerializer(typeof(ExampleModelTemplateSerializer ))]
public TemplateModel Template { get; set; }
}
Serializer
public class ExampleModelTemplateSerializer : SerializerBase<TemplateModel>
{
public override TemplateModel Deserialize(BsonDeserializationContext context, BsonDeserializationArgs args)
{
return context.Reader.CurrentBsonType == BsonType.String
? null
: base.Deserialize(context, args);
}
}
Exception
消息:ReadBsonType仅在State为Type时才能调用,而在状态就是价值。
您收到此错误的原因是context.Reader
仍然需要读取字符串,因此您可以调用context.Reader.ReadString();
但可以根据需要返回null
。
[下一个问题是您要在base.Deserialize()
上调用SerializerBase<T>
,这是一个抽象类,并且会引发异常(实现here)。因此,您需要通过调用BsonSerializer
:
public class ExampleModelTemplateSerializer : SerializerBase<TemplateModel>
{
public override TemplateModel Deserialize(BsonDeserializationContext context, BsonDeserializationArgs args)
{
if (context.Reader.CurrentBsonType == BsonType.String)
{
context.Reader.ReadString();
return null;
}
return BsonSerializer.Deserialize<TemplateModel>(context.Reader);
}
}