Che*_*Cat 6 c# list converter amazon-web-services amazon-dynamodb
我需要将IList<MyCustomType>as添加DynamoDBProperty到 DynamoDB 表中,其项目由类定义MyTableItem。
使用此AWS 文档页面中的信息,我实现了转换器 for MyCustomType(not for IList<MyCustomType>)。但是当创建一个新的时,MyTableItem我注意到该ToEntry()方法接收一个类型IList<MyCustomType>而不是MyCustomType.
阅读文档我了解到列表(List或IList,或一般的集合)是由 DynamoDB 自动处理的...
我怎样才能达到预期的结果?
这是代码:
// MyTableItem
[Serializable]
public class MyTableItem
{
[DynamoDBHashKey]
public string Id { get; set; }
[DynamoDBProperty]
public string Field1 { get; set; }
[DynamoDBProperty]
public string Field2 { get; set; }
// List of MyCustomType objects
[DynamoDBProperty(typeof(MyCustomTypeConverter))]
public IList<MyCustomType> CustomField { get; set; }
}
// MyCustomType
[Serializable]
public class MyCustomType
{
public string DocumentType { get; set; }
public string Status { get; set; }
public string Code { get; set; }
}
// Converter methods
public class MyCustomTypeConverter : IPropertyConverter
{
public DynamoDBEntry ToEntry(object value)
{
if (value == null)
return new Primitive { Value = null };
MyCustomType item = value as MyCustomType;
if (item == null)
throw new InvalidCastException("Cannot convert MyCustomType to DynamoDBEntry.");
string data = string.Format("{0};{1};{2}", item.DocumentType, item.Status, item.Code);
DynamoDBEntry entry = new Primitive { Value = data };
return entry;
}
public object FromEntry(DynamoDBEntry entry)
{
if (entry == null)
return new MyCustomType();
Primitive primitive = entry as Primitive;
if (primitive == null || !(primitive.Value is string) || string.IsNullOrEmpty((string)primitive.Value))
throw new InvalidCastException("Cannot convert DynamoDBEntry to MyCustomType.");
string[] data = ((string)(primitive.Value)).Split(new string[] { ";" }, StringSplitOptions.None);
if (data.Length != 3)
throw new ArgumentOutOfRangeException("Invalid arguments number.");
MyCustomType complexData = new MyCustomType
{
DocumentType = Convert.ToString(data[0]),
Status = Convert.ToString(data[1]),
Code = Convert.ToString(data[2])
};
return complexData;
}
}
Run Code Online (Sandbox Code Playgroud)
似乎 DynamoDb SDK序列化 没有问题IList<T>,反序列化确实有问题。只是猜测,但这可能是因为它不知道使用哪种具体类型。
我有一个与您类似的设置,我尝试更改我的文档以使用List<T>,并且 SDK 能够反序列化而无需添加任何自定义IPropertyConverter实现。
看起来完整的双向支持只有在您公开一个具体的 List 而不是接口时才存在。所以这是解决问题的一种可能方法。
但是,如果您想尝试解决问题,IList我将使用 SDK 实际发送给您的内容IList,而不是列表中的项目。对我来说,迭代该列表并将每个项目转换为条目列表是有意义的。对于反序列化,您将获得该条目集合,并且您可以构建一个新的模型列表。
TL;DR 如果可以,请使用列表,否则针对IList<T>not实现您的转换器T。