如何使用C#包装器更改Mongo DB属性的类型?

时间:2015-10-01 11:41:10

标签: c# mongodb

我正在使用Mongo DB的1.10 C#包装器。

我有这堂课:

public User
{
    public ObjectId SignatureImage;
}

我将同一字段的类型更改为:

public User
{
    public MyImageType SignatureImage;
}

然后我试图让这个反序列化器将存储的ObjectId转换为MyImageType类型。

public class ImageRelationSerializer : BsonBaseSerializer
{
    public override object Deserialize(BsonReader bsonReader, Type nominalType, Type actualType, IBsonSerializationOptions options)
    {
        if (bsonReader.CurrentBsonType == BsonType.ObjectId)
        {
            var _id = bsonReader.ReadObjectId();
            return ImageAPI.Load(_id);
        }
    }

    public override void Serialize(BsonWriter bsonWriter, Type nominalType, object value, IBsonSerializationOptions options)
    {
        ...
    }
}

我用这个注册Serializer类:

BsonClassMap.RegisterClassMap<User>(cm =>
{
    cm.AutoMap();
    cm.GetMemberMap(x => x.SignatureImage).SetSerializer(new ImageRelationSerializer());
});

然后我运行FindOneAs<User>Deserialize按预期执行。但如果它返回null,则“FindOneAs”方法会抛出Object reference not set to an instance of an object.异常,如果它返回MyImageType,则会得到Specified cast is not valid

我该如何解决这个问题?

0 个答案:

没有答案