将mongodb文档序列化为域对象

时间:2019-05-20 11:04:23

标签: c# mongodb mongodb-.net-driver mongodb-csharp-2.0

我正在尝试将mondodb文档读入我的域类(Company)中,但其中一个属性出现错误。 错误消息显示为:

  

“期望一个嵌套文档,它表示一个序列化形式的   OrgNumber值,但找到了String类型的值”

对象看起来像这样:

public class OrgNumber
{
    public string Value { get; private set; }
    ...

    private OrgNumber() { }

    public OrgNumber(string value) {
            Value = value;
    }
}

public class Company
{
    public string Name { get; private set; }
    public OrgNumber OrgNumber { get; private set; }
    ...

    private Company() { }

    public Company(string name, OrgNumber orgNumber)
    {
            Name = name;
            OrgNumber = orgNumber;
    }
}

mongodb文档如下所示:

{
"name": "Company name",
"orgNumber": "1234-5678",
}

我正在阅读文档并将其直接映射到我的域模型中:

var collection = _mongoDb.GetCollection<Company>("Companies");
var result = await collection.Find(c => c.CompanyId == companyId).SingleOrDefaultAsync();

如何正确地将OrgNumber的字符串表示形式转换为正确的类型OrgNumber

1 个答案:

答案 0 :(得分:0)

您可以继承SerializerBase<T>

创建自己的序列化程序
public class OrgNumberSerializer : SerializerBase<OrgNumber>
{
    public override OrgNumber Deserialize(BsonDeserializationContext context, BsonDeserializationArgs args)
    {
        var serializer = BsonSerializer.LookupSerializer(typeof(string));
        var data = serializer.Deserialize(context, args);
        return new OrgNumber(data.ToString());
    }

    public override void Serialize(BsonSerializationContext context, BsonSerializationArgs args, OrgNumber value)
    {
        var serializer = BsonSerializer.LookupSerializer(typeof(string));
        serializer.Serialize(context, value.Value);
    }
}

然后需要使用以下代码行对其进行全局注册:

BsonSerializer.RegisterSerializer(typeof(OrgNumber), new OrgNumberSerializer());

您可以找到有关here详细信息的更多信息