8

We need to be able to set table name based on build environment. Consider the following class:

[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; }
}

In serverless.yml, can the table name be set like this:

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

Then in the code we can load the table name dynamically based on the table name in the tableName variable. We prefer to use DynamoDBContext rather than DynamoDBv2.DocumentModel (which already has a solution here How do I dynamically change dynamodb tablename in c# using object persistence model)

Something like this in Java: https://medium.com/@onclouds/aws-lambda-use-different-dynamodb-tables-for-different-stages-5eda9f5378b2

2
  • 1
    Did you actually ask a question? How to Ask Your questions reads as a set of requirements Commented Sep 20, 2018 at 7:35
  • yeah, just edit the title to reflect that. Thanks. Commented Sep 20, 2018 at 7:48

1 Answer 1

15

Found a solution by passing a table name prefix:

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

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

You still have to name your table movies though:

[DynamoDBTable("movies")]
public class Movie

DynamoDBContext will add the prefix to the table name when loading the context. So it will try to load prod-movies, stag-movies.

Here is where the table prefix is used in AWS SDK internally

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)

Some references that helped me find the solution:

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

Sign up to request clarification or add additional context in comments.

1 Comment

Can we not remove [DynamoDBTable("movies")] attribute and use the full table name in TableNamePrefix ?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.