使用 .NET SDK 在 DynamoDB 中持久化动态对象

Persisting dynamic object in DynamoDB with .NET SDK(使用 .NET SDK 在 DynamoDB 中持久化动态对象)

本文介绍了使用 .NET SDK 在 DynamoDB 中持久化动态对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用 .NET SDK 将以下类持久化到 DynamoDB:

I'm trying to persist the following class to DynamoDB using the .NET SDK:

public class MyClass
{
    public string Id { get; set; }

    public string Name { get; set; }

    public object Settings { get; set; }
}

问题在于设置属性.它可以是任何类型的对象,我事先不知道可能分配给它什么.当我尝试将其持久化到 DynamoDB 时,出现以下异常:

The problem is with the Settings property. It can be any type of object, and I do not know in advance what might be assigned to it. When I try to persist it to DynamoDB, I get the following exception:

System.InvalidOperationException: 'Type System.Object is unsupported, it has no supported members'

Document Model 和 Object Persistence Model 方法都会导致相同的异常.

Both the Document Model and Object Persistence Model methods result in the same exception.

有没有办法将这些对象持久保存在 DynamoDB 中?其他数据库(如 MongoDB 和 Azure DocumentDB)可以毫无问题地执行此操作,并且可以将它们反序列化为带有鉴别器的正确类型,或作为动态 JSON 对象.

Is there a way to persist these objects in DynamoDB? Other databases like MongoDB and Azure DocumentDB will do this without any issue, and they can be deserialized to either the proper type with a discriminator, or as a dynamic JSON object.

推荐答案

您可以使用此处记录的一般方法:https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/DynamoDBContext.ArbitraryDataMapping.html

You can use the general approach documented here: https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/DynamoDBContext.ArbitraryDataMapping.html

这是我对任意对象的实现:

Here's my implementation for any arbitrary object:

public class DataConverter : IPropertyConverter
{
    public object FromEntry(DynamoDBEntry entry)
    {
        var primitive = entry as Primitive;
        if (primitive == null || !(primitive.Value is String) || string.IsNullOrEmpty((string)primitive.Value))
            throw new ArgumentOutOfRangeException();
        object ret = JsonConvert.DeserializeObject(primitive.Value as string);
        return ret;
    }

    public DynamoDBEntry ToEntry(object value)
    {
        var jsonString = JsonConvert.SerializeObject(value);
        DynamoDBEntry ret = new Primitive(jsonString);
        return ret;
    }
}

然后像这样注释您的属性:

Then annotate your property like this:

[DynamoDBProperty(typeof(DataConverter))]
public object data { get; set; }

这篇关于使用 .NET SDK 在 DynamoDB 中持久化动态对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:使用 .NET SDK 在 DynamoDB 中持久化动态对象

基础教程推荐