所以我有一个模型存储库,它使用适用于 Dynamo 的 C# AWS SDK。现在它有点丑陋。我想要的是将结果项目转换到我的模型中。进入 Dynamo 很棒。我只是对我的 Poco 类做了一些类型反射(reflection),然后像这样把它们塞进去:
var doc = new Document();
foreach (PropertyInfo prop in model.GetType().GetProperties(BindingFlags.Instance | BindingFlags.Public))
{
var propName = (string)prop.Name;
// dont add if value is null
if (prop.GetValue(model, null) != null)
{
if (prop.PropertyType == typeof(string))
doc[propName] = (string)prop.GetValue(model, null);
if (prop.PropertyType == typeof(List<string>))
doc[propName] = (List<string>)prop.GetValue(model, null);
if (prop.PropertyType == typeof(float))
doc[propName] = (float)prop.GetValue(model, null);
}
}
但是在 repo 中,我希望在检索项目时不必编写这种丑陋的手动转换。 是否有 AWS 助手来减少手动操作?我想我可以编写上述循环的逆过程并获取属性属性名称,然后在每个 N、S、SS 类型等上测试是否为 null。
var request = new ScanRequest
{
TableName = TableName.User,
};
var response = client.Scan(request);
var collection = (from item in response.ScanResult.Items
from att in item
select new User(att.Value.S, att.Value.N, att.Value.S, att.Value.N, att.Value.S, att.Value.S, att.Value.S, att.Value.S, att.Value.S,
att.Value.S, att.Value.S, att.Value.S, att.Value.S, att.Value.SS, att.Value.SS)).ToList();
return collection.AsQueryable();
最佳答案
您可以使用内置的 FromDocument
转换 Dictionary<string, AttributeValue>
的方法到你的类型 T 类
List<MyClass> result = new List<MyClass>();
var response = await client.QueryAsync(request);
foreach (Dictionary<string, AttributeValue> item in response.Items)
{
var doc = Document.FromAttributeMap(item);
var typedDoc = context.FromDocument<MyClass>(doc);
result.Add(typedDoc);
}
关于c# - AWS API : how to cast dynamo result as class,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14926167/