In this previous post, I showed how to update a property in a nested object in DynamoDb. In that post, the property was a simple string. In this short post, I’m going to show how to update an object property.
Let’s say our DynamoDB document looks like this
[DynamoDBTable("books")]
public class Book
{
[DynamoDBHashKey]
public Guid Id { get; set; }
public string Name { get; set; }
public Publisher Publisher { get; set; }
}
public class Publisher
{
public Guid Id { get; set; }
public string Name { get; set; }
}
We can use UpdateItemAsync to update only the Publisher property as followed
private readonly IAmazonDynamoDB _ddbClient; // This will be injected via DI
public async Task UpdatePublisher(Guid bookId, Publisher publisher)
{
await _ddbClient.UpdateItemAsync(new UpdateItemRequest
{
TableName = "books",
UpdateExpression = "SET Publisher = :ps",
Key = new Dictionary<string, AttributeValue>
{
{ "Id", new AttributeValue(bookId.ToString()) },
},
ExpressionAttributeValues = new Dictionary<string, AttributeValue>
{
{
":ps",
new AttributeValue
{
M = Document
.FromJson(JsonConvert.SerializeObject(publisher))
.ToAttributeMap()
}
},
}
});
}
This will work fine as long as publisher is not null. If publisher is null, which is a valid use case, we’ll get this exception.

Instead of setting the property to null, we need to remove it. Our method could then
become this to handle null.
private readonly IAmazonDynamoDB _ddbClient; // This will be injected via DI
public async Task UpdatePublisher(Guid bookId, Publisher publisher)
{
var updateExpression = publisher == null
? "REMOVE Publisher"
: "SET Publisher = :ps";
var expressionAttrValues = publisher == null
? new Dictionary<string, AttributeValue>()
: new Dictionary<string, AttributeValue>
{
{
":ps",
new AttributeValue
{
M = Document
.FromJson(JsonConvert.SerializeObject(publisher))
.ToAttributeMap()
}
},
};
await _ddbClient.UpdateItemAsync(new UpdateItemRequest
{
TableName = "books",
UpdateExpression = updateExpression,
Key = new Dictionary<string, AttributeValue>
{
{ "Id", new AttributeValue(bookId.ToString()) },
},
ExpressionAttributeValues = expressionAttrValues
});
}