如何使用无服务器和DynamoDBContext在dynamodb中动态设置表名?

时间:2018-09-20 07:33:00

标签: c# amazon-web-services amazon-dynamodb

我们需要能够根据构建环境设置表名称。考虑以下课程:

[DynamoDBTable("movies")]
public class Movie
{
    [DynamoDBHashKey]
    public string Title { get; set; }

    [DynamoDBRangeKey(AttributeName = "Released")]
    public DateTime ReleaseDate { get; set; }

    public List<string> Genres { get; set; }
}

serverless.yml中,可以这样设置表名:

functions:
    update-movies:
        environment:
            tableName: movies-prod

然后在代码中,我们可以基于tableName变量中的表名动态加载表名。我们更喜欢使用DynamoDBContext而不是DynamoDBv2.DocumentModelHow do I dynamically change dynamodb tablename in c# using object persistence model已有解决方案)

在Java中是这样的: https://medium.com/@onclouds/aws-lambda-use-different-dynamodb-tables-for-different-stages-5eda9f5378b2

1 个答案:

答案 0 :(得分:1)

通过传递表名前缀找到解决方案:

DynamoDBContextConfig config = new DynamoDBContextConfig()
{
    TableNamePrefix = "prod-"
};

_dynamoDBContext = new DynamoDBContext(new AmazonDynamoDBClient(), config);

尽管如此,您仍然必须命名表movies

[DynamoDBTable("movies")]
public class Movie

DynamoDBContext将在加载上下文时在表名前添加前缀。因此它将尝试加载prod-moviesstag-movies

此处是内部在AWS开发工具包中使用表前缀的位置

if (!string.IsNullOrEmpty(flatConfig.TableNamePrefix))
    tableName = flatConfig.TableNamePrefix + tableName;

https://github.com/aws/aws-sdk-net/blob/b691e46e57a3e24477e6a5fa2e849da44db7002f/sdk/src/Services/DynamoDBv2/Custom/DataModel/ContextInternal.cs

一些帮助我找到解决方案的参考文献:

https://aws.amazon.com/blogs/developer/enhancements-to-the-dynamodb-sdk/

https://github.com/aws/aws-sdk-net/blob/b691e46e57a3e24477e6a5fa2e849da44db7002f/sdk/test/Services/DynamoDBv2/UnitTests/Custom/DynamoDBTests.cs