c# - AWS API : how to cast dynamo result as class

标签 c# dynamic casting amazon-web-services amazon-dynamodb

所以我有一个模型存储库,它使用适用于 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/

相关文章:

c# - 数据源是无效类型。它必须是 IListSource、IEnumerable 或 IDataSource

delphi - Rtti 调用类方法显示无效类型转换

java - 如何修复列表中对象数组的不兼容类型

c# - SignalR 在 ASP .Net 5 RC-1 中不工作

c# - 无法删除数据库,因为它当前正在使用中

c# - 查询在 SQL Server 中直接在 4 秒内执行,但在 ASP.NET 中需要 > 30 秒?

dynamic - Erlang动态记录编辑

java - 在运行时 : works in some cases, 获取泛型类型,但在其他运行时获取泛型类型 - 为什么?

asp.net - 为什么 ASP.NET ViewState 保留为 asp :dropdownlist but not an asp:table?

java 将 Blob 插入为 ByteArrayOutputStream 获取 ClassCastException