PocoDynamo如何在运行时修改Put和Delete操作的表名?
Absolutely feasible! You can replicate the runtime table name modification pattern you used for queries with Put and Delete operations in PocoDynamo. There are two clean approaches to achieve this:
1. Expression-Based Modification (Per-Operation Control)
Just like you used QueryExpression<T> for queries, PocoDynamo provides equivalent expression types for write/delete operations: PutItemExpression<T> and DeleteItemExpression<T>. You can modify their TableName property before executing the operation.
First, update your Decorate method to handle any DynamoDB expression type (they all implement the IDynamoDbExpression<T> interface which exposes the TableName property):
private void Decorate<TPoco>(IDynamoDbExpression<TPoco> expression, string environment) { expression.TableName = $"{environment}-{expression.TableName}"; }
Example: Put Operation
private void SaveTelevision(Television tv) { var db = new PocoDynamo(_client); // Create a Put expression instead of using db.Put(tv) directly var putExpression = db.FromPut(tv); // Apply your environment-based table name decoration Decorate(putExpression, _environment); // Execute the operation putExpression.Exec(); }
Example: Delete Operation
private void DeleteTelevision(int tvId) { var db = new PocoDynamo(_client); // Create a Delete expression targeting the item by ID var deleteExpression = db.FromDelete<Television>(q => q.Id == tvId); // Apply the table name decoration Decorate(deleteExpression, _environment); // Execute the operation deleteExpression.Exec(); }
2. Global Table Name Configuration (One-Time Setup)
If you want all operations (Query, Put, Delete, etc.) to automatically use the environment-prefixed table name without manually decorating each expression, you can configure a global table name rule on your PocoDynamo instance:
// Initialize your PocoDynamo client with a global table name formatter var db = new PocoDynamo(_client); // Define a rule for your Television entity (repeat for other entities if needed) db.TableNames.Add<Television>(originalName => $"{_environment}-{originalName}"); // Now you can use the shortcut methods directly—no manual decoration needed! private void SaveTelevision(Television tv) { var db = new PocoDynamo(_client); db.TableNames.Add<Television>(name => $"{_environment}-{name}"); db.Put(tv); // Automatically uses "dev-Television" (or your environment prefix) } private void DeleteTelevision(int tvId) { var db = new PocoDynamo(_client); db.TableNames.Add<Television>(name => $"{_environment}-{name}"); db.Delete<Television>(tvId); // Uses the prefixed table name }
This global approach is cleaner if all your operations for an entity should use the same environment-prefixed table name.
内容的提问来源于stack exchange,提问作者Alex B

