Using Amazon DynamoDb with the AWS .NET API Part 5: updating and deleting records

Introduction

In the previous post we saw how to insert records into an Amazon DynamoDb table. We looked at two distinct programmatic ways to build our objects to be inserted: the loosely typed Document model and the strongly typed, more object oriented Data model.

In this post we’ll see how to update and delete records using the two models.

As a reminder we inserted the following records into our DynamoDb People table in the previous post:

Records saved in DynamoDb through data model

Open the demo console application we’ve been working on so far and let’s get to it!

Updates

For an update to work we’ll need to provide the primary key(s) depending on the primary key structure of the table. You’ll recall that we have a composite primary key of type Hash and Range. Those will be used to find the record to be updated – much like you provide an integer ID to find a record in an SQL database. We’ll look at each model in turn.

Document model

We’ll update the first Person object we inserted in the previous post – John. We’ll update his age to 38 and he’ll get a set of new neighbours. The following method in DynamoDbDemoService will do just that using the document model:

public void UpdatePeopleByDocumentModel(string tableName)
{
	try
	{
		using (IAmazonDynamoDB client = GetDynamoDbClient())
		{
			Table peopleTable = Table.LoadTable(client, tableName);
			Document firstPerson = new Document();
			firstPerson["Name"] = "John";
			firstPerson["Birthdate"] = new DateTime(1980, 06, 24);
			firstPerson["Age"] = 38;
			firstPerson["Neighbours"] = new List<String>() { "Evelyn", "Judy", "Sarah" };
			peopleTable.UpdateItem(firstPerson);
		}
	}
	catch (AmazonDynamoDBException exception)
	{
		Debug.WriteLine(string.Concat("Exception while updating a record in DynamoDb table: {0}", exception.Message));
		Debug.WriteLine(String.Concat("Error code: {0}, error type: {1}", exception.ErrorCode, exception.ErrorType));
	}
}

As you see this is almost identical to the code which inserts a Person object with the exception that we use the UpdateItem method. All properties which are not set in the dictionary will remain untouched. E.g. we didn’t set any value to the Address property so it will stay as it is.

Run the method from Main…

static void Main(string[] args)
{
	DynamoDbDemoService service = new DynamoDbDemoService();
	service.UpdatePeopleByDocumentModel("People");
}

…and we’ll see the updated row in the GUI:

Row updated using document model in Amazon DynamoDb

Data model

Updating an item using the data model is the same as how we inserted it using the DynamoDBContext.Save method. The Save method will update an item if there’s already one with the provided primary key(s). Here’s an example which updates the Address property of John:

public void UpdatePeopleByDataModel(string tableName)
{
	try
	{
		using (IAmazonDynamoDB client = GetDynamoDbClient())
		{
			DynamoDBContext context = new DynamoDBContext(client);
			Person firstPerson = new Person()
			{
				Name = "John"
				, BirthDate = new DateTime(1980, 06, 24)
				, Address = new Address() { Street = "60 Short Street", City = "Manchester", Country = "UK" }						
			};
			context.Save<Person>(firstPerson);
					
		}
	}
	catch (AmazonDynamoDBException exception)
	{
		Debug.WriteLine(string.Concat("Exception while updating a record in DynamoDb table: {0}", exception.Message));
		Debug.WriteLine(String.Concat("Error code: {0}, error type: {1}", exception.ErrorCode, exception.ErrorType));
	}
}

Calling it from Main…

static void Main(string[] args)
{
	DynamoDbDemoService service = new DynamoDbDemoService();
	service.UpdatePeopleByDataModel("People");
}

…will give John the new address:

Row updated using data model in Amazon DynamoDb

However, as you can see the age was set to 0 and Neighbours to an empty string. It is possible to “defend” our code against null values as follows using the DynamoDBOperationConfig object:

DynamoDBOperationConfig config = new DynamoDBOperationConfig();
config.IgnoreNullValues = true;			
context.Save<Person>(firstPerson, config);

…which will ignore the null value for the Neighbours property but still leaves Age at 0. So we need to set at least each primitive to its original value:

Person firstPerson = new Person()
{
	Name = "John"
	, BirthDate = new DateTime(1980, 06, 24)
	, Address = new Address() { Street = "60 Short Street", City = "Manchester", Country = "UK" }
	, Age = 38
};
DynamoDBOperationConfig config = new DynamoDBOperationConfig();
config.IgnoreNullValues = true;			
context.Save<Person>(firstPerson, config);

Deletions

Like above, we’ll need the primary key(s) in order to find which record is to be deleted. Here’s how to remove John using the two models:

Document model

public void DeletePersonByDocumentModel(string tableName)
{
	try
	{
		using (IAmazonDynamoDB client = GetDynamoDbClient())
		{
			Table peopleTable = Table.LoadTable(client, tableName);
			Document firstPerson = new Document();
			firstPerson["Name"] = "John";
			firstPerson["Birthdate"] = new DateTime(1980, 06, 24);
			peopleTable.DeleteItem(firstPerson);
		}
	}
	catch (AmazonDynamoDBException exception)
	{
		Debug.WriteLine(string.Concat("Exception while deleting a record in DynamoDb table: {0}", exception.Message));
		Debug.WriteLine(String.Concat("Error code: {0}, error type: {1}", exception.ErrorCode, exception.ErrorType));
	}
}

Data model

public void DeletePersonByDataModel(string tableName)
{
	try
	{
		using (IAmazonDynamoDB client = GetDynamoDbClient())
		{
			DynamoDBContext context = new DynamoDBContext(client);
			Person firstPerson = new Person()
			{
				Name = "John"
				, BirthDate = new DateTime(1980, 06, 24)						
			};
			context.Delete<Person>(firstPerson);
		}
	}
	catch (AmazonDynamoDBException exception)
	{
		Debug.WriteLine(string.Concat("Exception while deleting a record in DynamoDb table: {0}", exception.Message));
		Debug.WriteLine(String.Concat("Error code: {0}, error type: {1}", exception.ErrorCode, exception.ErrorType));
	}
}

…and we’re saying goodbye to John:

Item deleted from Amazon DynamoDb

We’ll look at queries in the next post.

View all posts related to Amazon Web Services and Big Data here.

Advertisements

About Andras Nemes
I'm a .NET/Java developer living and working in Stockholm, Sweden.

3 Responses to Using Amazon DynamoDb with the AWS .NET API Part 5: updating and deleting records

  1. Darrell says:

    Andras, How would you change just one of his neighbors without replacing the entire list?

    • Andras Nemes says:

      Hi Darrell,

      Do you mean like “update Judy set Susan” for “John”? I don’t think it’s possible, you’ll need to send in the full list with the new/removed neighbours.

      //Andras

      • Darrell says:

        Thank you. That explains why I could not find anything in the documentation or samples about it.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

ultimatemindsettoday

A great WordPress.com site

Elliot Balynn's Blog

A directory of wonderful thoughts

Robin Sedlaczek's Blog

Developer on Microsoft Technologies

HarsH ReaLiTy

My goal with this blog is to offend everyone in the world at least once with my words… so no one has a reason to have a heightened sense of themselves. We are all ignorant, we are all found wanting, we are all bad people sometimes.

Softwarearchitektur in der Praxis

Wissenswertes zu Webentwicklung, Domain-Driven Design und Microservices

the software architecture

thoughts, ideas, diagrams,enterprise code, design pattern , solution designs

Technology Talks

on Microsoft technologies, Web, Android and others

Software Engineering

Web development

Disparate Opinions

Various tidbits

chsakell's Blog

Anything around ASP.NET MVC,WEB API, WCF, Entity Framework & AngularJS

Cyber Matters

Bite-size insight on Cyber Security for the not too technical.

Guru N Guns's

OneSolution To dOTnET.

Johnny Zraiby

Measuring programming progress by lines of code is like measuring aircraft building progress by weight.

%d bloggers like this: