AWS .NET SDK
AWS Guide for .NET Developers

Selecting an Amazon DynamoDB Programming Model

The AWS SDK for .NET supports Amazon DynamoDB, which is a fast NoSQL database service offered by AWS. The SDK provides three programming models for communicating with DynamoDB: low-level, document, and object persistence.

The following information introduces these models and their APIs, provides examples for how and when to use them, and gives you links to additional DynamoDB programming resources in the AWS SDK for .NET.

Low-Level Model

The low-level programming model wraps direct calls to the DynamoDB service. You access this model through the Amazon.DynamoDBv2 namespace.

Of the three models, the low-level model requires you to write the most code. For example, you must convert .NET data types to their equivalents in DynamoDB. However, this model gives you access to the most features.

The following examples show you how to use the low-level model to create a table, modify a table, and insert items into a table in DynamoDB.

Create a Table

In the following example, you create a table by using the CreateTable method of the AmazonDynamoDBClient class. The CreateTable method uses an instance of the CreateTableRequest class that contains characteristics such as required item attribute names, primary key definition, and throughput capacity. The CreateTable method returns an instance of the CreateTableResponse class.

// using Amazon.DynamoDBv2; // using Amazon.DynamoDBv2.Model; var client = new AmazonDynamoDBClient(); Console.WriteLine("Getting list of tables"); List<string> currentTables = client.ListTables().TableNames; Console.WriteLine("Number of tables: " + currentTables.Count); if (!currentTables.Contains("AnimalsInventory")) { var request = new CreateTableRequest { TableName = "AnimalsInventory", AttributeDefinitions = new List<AttributeDefinition> { new AttributeDefinition { AttributeName = "Id", // "S" = string, "N" = number, and so on. AttributeType = "N" }, new AttributeDefinition { AttributeName = "Type", AttributeType = "S" } }, KeySchema = new List<KeySchemaElement> { new KeySchemaElement { AttributeName = "Id", // "HASH" = hash key, "RANGE" = range key. KeyType = "HASH" }, new KeySchemaElement { AttributeName = "Type", KeyType = "RANGE" }, }, ProvisionedThroughput = new ProvisionedThroughput { ReadCapacityUnits = 10, WriteCapacityUnits = 5 }, }; var response = client.CreateTable(request); Console.WriteLine("Table created with request ID: " + response.ResponseMetadata.RequestId); }

Insert an Item into a Table

In the following example, you use the low-level model to insert two items into a table in DynamoDB. Each item is inserted through the PutItem method of the AmazonDynamoDBClient class, using an instance of the PutItemRequest class. Each of the two instances of the PutItemRequest class takes the name of the table that the items will be inserted in, with a series of item attribute values.

// using Amazon.DynamoDBv2; // using Amazon.DynamoDBv2.Model; var client = new AmazonDynamoDBClient(); var request1 = new PutItemRequest { TableName = "AnimalsInventory", Item = new Dictionary<string, AttributeValue> { { "Id", new AttributeValue { N = "1" }}, { "Type", new AttributeValue { S = "Dog" }}, { "Name", new AttributeValue { S = "Fido" }} } }; var request2 = new PutItemRequest { TableName = "AnimalsInventory", Item = new Dictionary<string, AttributeValue> { { "Id", new AttributeValue { N = "2" }}, { "Type", new AttributeValue { S = "Cat" }}, { "Name", new AttributeValue { S = "Patches" }} } }; client.PutItem(request1); client.PutItem(request2);

Reading an Item from a Table

The following example features the Amazon.DynamoDBv2.AmazonDynamoDBClient.GetItem method and a set of expressions to get and then print the item that has an Id of 205. Only the following attributes of the item are returned: Id, Title, Description, Color, RelatedItems, Pictures, and ProductReviews.

// using Amazon.DynamoDBv2; // using Amazon.DynamoDBv2.Model; var client = new AmazonDynamoDBClient(); var request = new GetItemRequest { TableName = "ProductCatalog", ProjectionExpression = "Id, Title, Description, Color, #ri, Pictures, #pr", ExpressionAttributeNames = new Dictionary<string, string> { { "#pr", "ProductReviews" }, { "#ri", "RelatedItems" } }, Key = new Dictionary<string, AttributeValue> { { "Id", new AttributeValue { N = "205" } } }, }; var response = client.GetItem(request);

In the preceding example, the ProjectionExpression property specifies the attributes to return. The ExpressionAttributeNames property specifies the placeholder #pr to represent the ProductReviews attribute and the placeholder #ri to represent the RelatedItems attribute.

Document Model

The document programming model provides an easier way to work with data in DynamoDB. This model is specifically intended for accessing tables and items in tables. You access this model through the Amazon.DynamoDBv2.DocumentModel namespace.

Compared to the low-level programming model, the document model is easier to code against DynamoDB data. For example, you don't have to convert as many .NET data types to their equivalents in DynamoDB. However, this model doesn't provide access to as many features as the low-level programming model. For example, you can use this model to create, retrieve, update, and delete items in tables. However, to create the tables, you must use the low-level model. Compared to the object persistence model, this model requires you to write more code to store, load, and query .NET objects.

The following examples show you how to use the document model to insert items and get items in tables in DynamoDB.

Insert an Item into a Table

In the following example, an item is inserted into a table through the PutItem method of the Table class. The PutItem method takes an instance of the Document class; the Document class is simply a collection of initialized attributes. To determine the table to insert the item into, call the LoadTable method of the Table class, specifying an instance of the AmazonDynamoDBClient class and the name of the target table in DynamoDB.

// using Amazon.DynamoDBv2; // using Amazon.DynamoDBv2.DocumentModel; var client = new AmazonDynamoDBClient(); var table = Table.LoadTable(client, "AnimalsInventory"); var item = new Document(); item["Id"] = 3; item["Type"] = "Horse"; item["Name"] = "Shadow"; table.PutItem(item);

Get an Item from a Table

In the following example, the item is retrieved through the GetItem method of the Table class. To determine the item to get, the GetItem method uses the hash-and-range primary key of the target item. To determine the table to get the item from, the LoadTable method of the Table class uses an instance of the AmazonDynamoDBClient class and the name of the target table in DynamoDB.

// using Amazon.DynamoDBv2; // using Amazon.DynamoDBv2.DocumentModel; var client = new AmazonDynamoDBClient(); var table = Table.LoadTable(client, "AnimalsInventory"); var item = table.GetItem(3, "Horse"); Console.WriteLine("Id = " + item["Id"]); Console.WriteLine("Type = " + item["Type"]); Console.WriteLine("Name = " + item["Name"]);

The preceding example implicitly converts the attribute values for Id, Type, and Name to strings for the WriteLine method. You can do explicit conversions by using the various AsType methods of the DynamoDBEntry class. For example, you could explicitly convert the attribute value for Id from a Primitive data type to an integer through the AsInt method.

int id = item["Id"].AsInt();

Or, you could perform an explicit cast here by using (int).

int id = (int)item["Id"];

Object Persistence Model

The object persistence programming model is specifically designed for storing, loading, and querying .NET objects in DynamoDB. You access this model through the Amazon.DynamoDBv2.DataModel namespace.

Of the three models, the object persistence model is the easiest to code against whenever you are storing, loading, or querying DynamoDB data. For example, you work with DynamoDB data types directly. However, this model provides access only to operations that store, load, and query .NET objects in DynamoDB. For example, you can use this model to create, retrieve, update, and delete items in tables. However, you must first create your tables using the low-level model, and then use this model to map your .NET classes to the tables.

The following examples show you how to define a .NET class that represents an item, use an instance of the .NET class to insert an item, and use an instance of a .NET object to get an item from a table in DynamoDB.

Define a .NET Class that Represents an Item in a Table

In the following example, the DynamoDBTable attribute specifies the table name, while the DynamoDBHashKey and DynamoDBRangeKey attributes model the table's hash-and-range primary key.

// using Amazon.DynamoDBv2.DataModel; [DynamoDBTable("AnimalsInventory")] class Item { [DynamoDBHashKey] public int Id { get; set; } [DynamoDBRangeKey] public string Type { get; set; } public string Name { get; set; } }

Use an Instance of the .NET Class to Insert an Item into a Table

In this example, the item is inserted through the Save method of the DynamoDBContext class. This takes an initialized instance of the .NET class that represents the item. (The instance of the DynamoDBContext class is initialized with an instance of the AmazonDynamoDBClient class.)

// using Amazon.DynamoDBv2; // using Amazon.DynamoDBv2.DataModel; var client = new AmazonDynamoDBClient(); var context = new DynamoDBContext(client); var item = new Item { Id = 4, Type = "Fish", Name = "Goldie" }; context.Save(item);

Use an Instance of a .NET Object to Get an Item from a Table

In this example, the item is retrieved through the Load method of the DynamoDBContext class. This takes a partially initialized instance of the .NET class that represents the hash-and-range primary key of the item to retrieve. (As shown previously, the instance of the DynamoDBContext class is initialized with an instance of the AmazonDynamoDBClient class.)

// using Amazon.DynamoDBv2; // using Amazon.DynamoDBv2.DataModel; var client = new AmazonDynamoDBClient(); var context = new DynamoDBContext(client); var item = context.Load<Item>(4, "Fish"); Console.WriteLine("Id = {0}", item.Id); Console.WriteLine("Type = {0}", item.Type); Console.WriteLine("Name = {0}", item.Name);