C#MongoDB序列化转换属性“仅当State为Type时才能调用ReadBsonType,而State为Value时不能调用。”

时间:2019-04-23 17:53:35

标签: c# mongodb mongodb.driver

我有一个要反序列化的模型,问题是在其中一个属性上,它有时是字符串,有时是文档。因此,我决定编写一个基于SerializerBase构建的自定义序列化程序。但是,似乎框架中可能存在错误。覆盖Deserialize方法时,总是会收到异常“ Re​​adBsonType仅在State为Type时才能调用,而在State为Value时才可以调用。”

我正在使用.Net Framework 4.6.2,而我的mongo库的所有版本均为2.8.0

这是我的课程的简化版本以及实现方式。

public class MyClassSerializer : SerializerBase<string>
{
    public override string Deserialize(BsonDeserializationContext context, BsonDeserializationArgs args)
    {
        // ultimately I will have some logic here but for now just trying to get this to not throw an error.
        return string.Empty;
    }
}

这是我要反序列化的模型:

public class FormData
{
    [BsonId]
    public string Id { get; set; }

    [BsonSerializer(typeof(MyClassSerializer))]
    public string Data { get; set; }
}

这似乎是一种非常现成的解决方案,任何人都可以看到我可能在做错什么吗?另外,由于我正在尝试编写一个可以处理类型转换的自定义序列化程序,因此是否可能有更合适的方法来实现此目的?

谢谢!

编辑:以下是我得到的堆栈跟踪:

  在MongoDB.Bson.Serialization.BsonClassMapSerializer 1.DeserializeMemberValue(BsonDeserializationContext context, BsonMemberMap memberMap) at MongoDB.Bson.Serialization.BsonClassMapSerializer上的

1。 .CursorBatchDeserializationHelper.DeserializeBatch [TDocument](RawBsonArray批处理,IBsonSerializer`1 documentSerializer,

3 个答案:

答案 0 :(得分:0)

您将类更改为对象该怎么办?我遇到了类似的问题,并且可行。

<td class="text-center"><?php echo $this->translate("Duration") ?> <?php echo "<br>"; ?>  <label class="label label-info"><?php echo $this->totals['tempo']; ?></label></td>

答案 1 :(得分:0)

我最终为模型本身而不是特定的属性编写了序列化程序,现在可以使用了。

答案 2 :(得分:0)

使用此代码

public class MyClass {
public ObjectId Id { get; set; }
[BsonSerializer(typeof(MyCustomStringSerializer))]
public string X { get; set; }
}

BsonClassMap.RegisterClassMap<MyClass>(cm => {
cm.AutoMap();
cm.GetMemberMap(c => c.X).SetSerializer(new MyCustomStringSerializer());
});