AWS API:如何将dynamo结果转换为类

Fla*_*ape 1 c# casting dynamic amazon-web-services amazon-dynamodb

所以我有一个模型存储库,它使用C#AWS SDK for Dynamo.现在它有点难看.我想要的是将结果项输出到我的模型中.进入Dynamo很棒.我只是对我的Poco类进行了一些类型的反射,然后将它们推入:

     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);
         }
     }
Run Code Online (Sandbox Code Playgroud)

但是在回购中,我想在检索项目时不必写这个丑陋的手工演员.是否有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();
Run Code Online (Sandbox Code Playgroud)

Vik*_*hee 9

您可以使用内置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);
        }
Run Code Online (Sandbox Code Playgroud)

  • 你的例子中的“上下文”是什么?它从哪里来? (2认同)

Pav*_*nov 5

您可以使用.NET SDK对象持久性模型功能.这允许您使用属性注释.NET对象,然后指导SDK如何将数据存储在DynamoDB中.