shawhu
shawhu

Reputation: 1237

How do I dynamically change dynamodb tablename in c# using object persistence model

I was using dynamodb Object Persistence model.

DynamoDBTable("mydynamodbtablename")]
public class mytable
{
  ....
}

problem is now if I tried to make the name of the table to change dynamically in runtime (I get table names through config files), I get errors

var Table_Name = Config.GetTableName();
DynamoDBTable(Table_Name)]
public class mytable
{
  ....
}

error: An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type xxx

Is there a way (easy way) so that I can still use DDB Object Persistence Model and make tables name dynamic?

Update:

It seems that I didn't mentioned ddb persistence model clearly. Here is the official document http://docs.aws.amazon.com/amazondynamodb/latest/developerguide/CRUDHighLevelExample1.html

and here is an example of how in real practice do we use object persistence model

var records = await context.LoadAsync<mytable>(somekey);
foreach(var item in records)
{
   ....
}

Upvotes: 11

Views: 5904

Answers (3)

Esben Skov Pedersen
Esben Skov Pedersen

Reputation: 4517

If you want to do it for the whole app(which I guess is the case since you mention config files) you should use the overload of DynamocDBContext which takes a DynamoDBContextConfig. e.g. in dotnet core you would do:

services.AddTransient<IDynamoDBContext>(c => new 
DynamoDBContext(c.GetService<IAmazonDynamoDB>(),
                new DynamoDBContextConfig 
                { 
                    TableNamePrefix = Configuration.GetValue("MyEnvironment", "unspecified")  + "-" 
                }));

Upvotes: 6

Jeroen Kok
Jeroen Kok

Reputation: 461

Use the overload of the LoadAsync<T> method that accepts a DynamoDBOperationConfig:

var config = new DynamoDBOperationConfig 
{ 
    OverrideTableName = "MyTableName"
};
var records = await context.LoadAsync<mytable>(somekey, config);
foreach(var item in records)
{
   ....
}

Upvotes: 24

notionquest
notionquest

Reputation: 39196

The main classes on Document Model are Table and Document. The Table class has the different APIs to perform the database operations (PutItem, GetItem, DeleteItem)

When you load the table using LoadTable API, you can set the TableConfig to override the table name values.

public Table LoadTable(
         IAmazonDynamoDB ddbClient,
         TableConfig config
)

The API accepts the TableConfig parameter. The TableConfig class has methods to override the table name.

Amazon.DynamoDBv2.DocumentModel.TableConfig 
TableName

Example:-

You can set the tableName on tableConfig object.

// Set up the Table object
var tableConfig = new TableConfig("tableName");
Table table = Table.LoadTable(client, tableConfig);
Document document = table.GetItem(101); // Primary key 101.

Upvotes: 2

Related Questions