Skip to main content

DynamoDB CRUD Operations in C#

Perform type-safe Create, Read, Update, and Delete operations on DynamoDB using FluentDynamoDB. This guide demonstrates the three API patterns available: Lambda/Fluent (recommended), String Formatted, and Manual Builder.

Create (Put)

var user = new User
{
UserId = "user123",
Email = "john@example.com",
Name = "John Doe"
};

// Simple put
await table.Users.PutAsync(user);

// Conditional put (prevent overwrite)
await table.Users.Put(user)
.Where(x => x.UserId.AttributeNotExists())
.PutAsync();

Read (Get)

// Simple get
var user = await table.Users.GetAsync("user123");

// Get with composite key
var order = await table.Orders.GetAsync("customer123", "order456");

// Consistent read
var response = await table.Users.Get("user123")
.UsingConsistentRead()
.GetItemAsync();

Update

// Update specific attributes
await table.Users.Update("user123")
.Set(x => new UserUpdateModel
{
Name = "Jane Doe",
UpdatedAt = DateTime.UtcNow
})
.UpdateAsync();

// Conditional update
await table.Users.Update("user123")
.Where(x => x.Status == "active")
.Set(x => new UserUpdateModel { Name = "Jane Doe" })
.UpdateAsync();

// Increment a counter
await table.Users.Update("user123")
.Set(x => new UserUpdateModel { LoginCount = x.LoginCount.Add(1) })
.UpdateAsync();

Delete

// Simple delete
await table.Users.DeleteAsync("user123");

// Conditional delete
await table.Users.Delete("user123")
.Where(x => x.Status == "inactive")
.DeleteAsync();

// Delete with composite key
await table.Orders.DeleteAsync("customer123", "order456");

Entity Definition

All examples above use this entity definition:

[DynamoDbTable("users")]
public partial class User
{
[PartitionKey]
[DynamoDbAttribute("pk")]
public string UserId { get; set; } = string.Empty;

[DynamoDbAttribute("email")]
public string Email { get; set; } = string.Empty;

[DynamoDbAttribute("name")]
public string Name { get; set; } = string.Empty;

[DynamoDbAttribute("status")]
public string Status { get; set; } = "active";

[DynamoDbAttribute("login_count")]
public int LoginCount { get; set; }
}

Learn More