Skip to main content

DynamoDB Entity Definitions in C#

Define type-safe DynamoDB entities in C# using FluentDynamoDB's source generator. This guide shows you how to create entities with partition keys, sort keys, Global Secondary Indexes (GSIs), and Local Secondary Indexes (LSIs) using simple attribute decorations.

Simple Table with Partition Key

The most basic entity requires a table name, partition key, and attribute mappings:

using Oproto.FluentDynamoDb.Attributes;

[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;
}

Table with Partition Key and Sort Key

Add a sort key for composite primary keys:

[DynamoDbTable("orders")]
public partial class Order
{
[PartitionKey]
[DynamoDbAttribute("pk")]
public string CustomerId { get; set; } = string.Empty;

[SortKey]
[DynamoDbAttribute("sk")]
public string OrderId { get; set; } = string.Empty;

[DynamoDbAttribute("total")]
public decimal Total { get; set; }

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

Using Key Prefixes

Add prefixes for single-table design patterns:

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

[SortKey(Prefix = "PROFILE")]
[DynamoDbAttribute("sk")]
public string ProfileType { get; set; } = "MAIN";
}

// Generated key builders:
// UserKeys.Pk("user123") → "USER#user123"
// UserKeys.Sk("MAIN") → "PROFILE#MAIN"

Learn More