Search code examples
c#amazon-web-servicesservicestackamazon-dynamodbpocodynamo

how do a conditional write in dynamodb with ServiceStack.Aws


In dynamodb, you can do a conditional write (see here and here).

Now, i'm using ServiceStack.Aws and i want to know how can achieve this (conditional writes)

My code looks like this

var awsDb = new AmazonDynamoDBClient();
var db = new PocoDynamo(awsDb);
db.UpdateItem<Country>(new Country{CountryId = 1, Name = "New Name"});

My model looks like this

[Alias("TABLE-NAME")]
public class Country
{
    [AutoIncrement]
    public int CountryId { get; set; }
    public string Name { get; set; }
    public string Culture { get; set; }
    public int State { get; set; }
}

But i want to update this item only if have a "state" property in 0


Solution

  • I've just added Typed UpdateExpression support in this commit which will let you use an expression builder for constructing an Update query which you can use it like:

    var q = db.UpdateExpression<Country>(1)
        .Set(() => new Country { Name = "New Name" })
        .Condition(x => x.State == 0);
    
    bool wasUpdated = db.Update(q);
    

    Just like PocoDynamo's Query and Scan Expression builders, UpdateExpression<T> inherits AWS's UpdateItemRequest which you can use to further customize the UpdateItemRequest before sending it. Also when a feature is not covered in PocoDynamo you can access AWS's underlying Dynamo DB client with db.DynamoDb.

    The new UpdateExpression<T> builder is available from v4.0.61 that's now available on MyGet.