Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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)
{
   ....
}
like image 741
shawhu Avatar asked May 18 '17 08:05

shawhu


2 Answers

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)
{
   ....
}
like image 148
Jeroen Kok Avatar answered Oct 18 '22 20:10

Jeroen Kok


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")  + "-" 
                }));
like image 35
Esben Skov Pedersen Avatar answered Oct 18 '22 22:10

Esben Skov Pedersen