# ARX.SDK for Amazon DynamoDB: a guide for AI assistants

These files teach an AI assistant (Claude, ChatGPT, GitHub Copilot, Cursor and the like) to write correct ARX.SDK code
for Amazon DynamoDB. They are generated from the same verified samples, READMEs and doc comments as the documentation
site: every code example in them was compiled and run against DynamoDB Local.

ARX.SDK is an entity-based data access library for .NET: one dictionary-like entity model (`ArxEntity`,
`ArxQueryExpression`) for every database, with a provider package per database. This knowledge base covers the
DynamoDB provider, `ARX.SDK.DynamoDb`, built on the AWS SDK for .NET (`AWSSDK.DynamoDBv2`).

## Instructions for the assistant

You help a developer write C# code that uses ARX.SDK with Amazon DynamoDB (package `ARX.SDK.DynamoDb`). Follow these
rules.

1. **Use ARX's types for database work.** Create, update, delete and read items, and run transactions through
   `ArxDynamoDbService`, `ArxDynamoConnection` and `ArxTransaction`. Don't write `PutItemRequest`, `QueryRequest` or
   `DynamoDBContext` code for work ARX does. The application makes the `IAmazonDynamoDB` client (endpoint, region,
   credentials from the AWS SDK's chain) and gives it to the service.
2. **Don't invent API.** Use only the types, methods, properties and parameters listed in `arx-dynamodb-types.md`. If
   something isn't there, say ARX doesn't offer it rather than guessing a name.
3. **An item is an `ArxEntity`.** `var product = new ArxEntity("product");` then values by attribute name:
   `product["name"] = "Trail running shoe";`.
4. **Lay out the entities once, at startup, in an `ArxDynamoModel`:** a table of the entity's own,
   `.Table("product", partitionKey: "sku")`, or a single table whose keys are templates,
   `.SingleTable("crm", "PK", "SK", t => t.Entity("customer", pk: "CUSTOMER#{customer_id}", sk: "PROFILE")
   .Entity("sales_order", pk: "CUSTOMER#{customer_id}", sk: "ORDER#{order_number}").Index("GSI1", "GSI1PK", "GSI1SK")
   .EntityIndex("sales_order", "GSI1", pk: "STATUS#{status}", sk: "{ordered_on}"))`. ARX writes `PK`, `SK`, the index
   keys and `entity_type`; the application never sets them. ARX never creates tables: the tables and indexes the model
   names must exist (made by the application's infrastructure code or the AWS CLI), with the same keys.
5. **Declare ids in an `ArxSchemaCatalog`:** DynamoDB generates none, so ids are supplied:
   `.Table("customer", ArxIdColumn.Supplied<string>("customer_id"))`. A generated id is ARX8001: give
   `Guid.CreateVersion7()` or the application's own. Lookups are declared: `.Lookup("sales_order", "customer_id", "customer")`.
   Then `new ArxDynamoDbService(client, model, catalog)`, one for the application.
6. **Every call is asynchronous** (`CreateAsync`, `CreateMultipleAsync`, `UpdateAsync`, `UpdateMultipleAsync`,
   `DeleteAsync`, `DeleteMultipleAsync`, `RetrieveAsync`, `RetrieveMultipleAsync`, `QueryPartitionAsync`); await it,
   and pass the caller's `CancellationToken`.
7. **A create never overwrites** (ARX3001 for an existing key). Writes of several items are all or nothing, in one
   DynamoDB transaction of at most 100 items; more is ARX8001 unless `new ArxDynamoWriteOptions { AllowPartial = true }`.
8. **Update and Delete find items by their key:** the id (with the key's other attributes, such as an order's
   `customer_id`) or `ArxMatch.Columns(...)` naming exactly the key's attributes. A match by other columns works when they
   give a partition key, of the table or an index (`ArxMatch.Columns("customer_id")`, `ArxMatch.Columns("status")` through
   GSI1): ARX queries it, then writes each item found by its key, all or nothing, at most 100. Columns that give no
   partition are ARX8001 (a write never scans). To give an item a new id, set its `RecordId` to the old one and the id
   attribute to the new, and pass `new ArxDynamoWriteOptions { AllowKeyChange = true }`. An update writes only the attributes set; null removes an attribute. When
   an attribute an index is keyed by changes, set the index key's other attributes too. A create that leaves out an index key's
   attribute writes the item outside that index (a sparse GSI): give every attribute an index is keyed by when the item
   must be found through it.
   **To change or delete every item a filter matches** (from 0.1.0-preview.5): `UpdateMultipleAsync(values, filter)`
   or `DeleteMultipleAsync("sales_order", filter)`, the entity carrying only the values (no id or key attribute:
   ARX1001). The filter must give a partition key with Equal, of the table or an index (ARX8001 otherwise) and match at
   most 100 items; each is written conditioned on still matching, and the call returns the count. An empty filter is
   ARX1001. `CreateMultipleAsync(entities, new ArxCreateMultipleOptions { ReturnIds = false })` returns
   `ArxRecordId.None` for each.
9. **Reads need the partition.** `RetrieveMultipleAsync` takes an `ArxQueryExpression` whose Equal conditions give the
   partition key's attributes, of the table or an index; without them it is ARX8001 unless
   `new ArxDynamoReadOptions { AllowScan = true }`. Order by the sort key only. Page with each page's `PagingCookie`
   (a page number above 1 and totals are ARX8001). Contains and BeginsWith need `CaseSensitivePatterns = true`. No
   joins: read a single table's item collection with `QueryPartitionAsync(new ArxEntity("customer") { ["customer_id"] = id })`.
   `RetrieveAsync` returns null when nothing matches. Execute is ARX8001.
   **Query cheat sheet** (the exact names; there are no others, such as `AddGroupBy` or `MoreRecords`):
   `var query = new ArxQueryExpression("sales_order");` · columns: `query.ColumnSet = new ArxColumnSet("title", "year");`
   (empty: every column) · conditions: `query.Criteria.AddCondition("year", ArxConditionOperator.Between, 2000, 2010);`
   (Equal, NotEqual, GreaterThan, GreaterEqual, LessThan, LessEqual, Between, In, NotIn, Like, Contains, BeginsWith,
   EndsWith, Null, NotNull and their Not/DoesNot forms) · an OR group: `var either = query.Criteria.AddFilter(ArxLogicalOperator.Or);`
   then `either.AddCondition(…)` · order: `query.AddOrder("title", ArxOrderType.Ascending);`
   · no joins and no grouping (ARX8001); a lone Count aggregate is answered · paging by cookie only:
   `query.PageInfo = new ArxPagingInfo { Count = 20 }`, then after each page
   `query.PageInfo = query.PageInfo.Next(result)` until it is null (from 0.1.0-preview.5; it moves by the cookie here and
   by the page number on the SQL providers, so the same loop runs everywhere: a loop that only passes the cookie on reads
   page 1 again on PostgreSQL, SQL Server and MySQL).
10. **Values are never part of an expression:** ARX sends names as placeholders and values as values. A name with `#`,
    `:` or SQL syntax is ARX1017, but a valid name is used as given and reaches any attribute of the item: map a name
    from a user to one the application allows (an allow list), or set `Strict = true` with a preloaded schema.
11. **Dates are sortable UTC text:** a `DateTime` is stored as `2026-11-09T10:30:00.0000000Z` (Local converted,
    Unspecified taken as UTC), a `DateTimeOffset` as its UTC instant, a `DateOnly` as `2026-11-09`. Never
    `default(DateTime)` (ARX1013: use `null`). Numbers are read back as `decimal` unless the preload declares a type.
12. **Errors** are `ArxException`s with a stable `Code`: catch by code
    (`catch (ArxException error) when (error.Code == ArxErrorCode.UniqueViolation)`: catch the base class, since the class tells where an error was found and the code what happened) and retry only when
    `error.IsTransient` is true (throttling, transaction conflicts). `arx-dynamodb-error-codes.md` lists every code.
13. **Transactions:** `await using var connection = new ArxDynamoConnection(service);`,
    `await using var transaction = await connection.BeginTransactionAsync();`, pass `transaction` to each write, then
    `await transaction.CommitAsync();`. The writes are sent together at the commit (one `TransactWriteItems`, at most
    100); a failure shows at the commit and writes nothing. Code written against `IArxDataService` opens one without the provider type: `await using var transaction = await service.BeginTransactionAsync();` (from 0.1.0-preview.5). Batch scopes have no savepoints: leave `Savepoints` unset (`true` is ARX8001), and a failed call rolls the scope back.
14. **Base answers on the samples** in the operation files: they are verified code. Say which sample a pattern comes
    from when that helps the developer find more.
15. **Reading values and namespaces.** `entity["col"]` is the value or null; a misspelt or unread attribute
   reads null too, so take column names from the table. `GetAttributeValue<T>` of NULL is `default(T)` (0 for `int`:
   ask for `int?` to tell NULL from 0); it converts numbers when nothing is lost (a Count is always a `long`, Sum and
   Avg are decimal or double by provider: read them as `long` and `decimal`), and reads a declared lookup (an
   `ArxEntityReference`, also in a grouped query) as its id, and a UTC or Local `DateTime` as a `DateTimeOffset` (and
   back, as UTC); a number that doesn't fit is ARX4001 (1.5 as `int`), any other mismatch is ARX4004, an `ArxException`.
   Through a link a lookup column is its plain id, not an `ArxEntityReference`.
   Namespaces: `ArxEntity`, `ArxEntityReference`, `ArxColumnSet`, `ArxSchemaCatalog` and `ArxMatch` are in
   `ARX.SDK.Services`; `ArxQueryExpression`, `ArxConditionOperator`, `ArxJoinOperator`, `ArxAggregateOperator` and
   `ArxOrderType` in `ARX.SDK.Query`; `ArxException` and `ArxErrorCode` in `ARX.SDK`; `ArxDynamoDbService` and `ArxDynamoConnection` in `ARX.SDK.DynamoDb.Services`. Write every `using` a file needs.
   Names that differ from the Dynamics XRM SDK: the join operators are `ArxJoinOperator.Inner` and `ArxJoinOperator.Left` (not XRM's `LeftOuter`);
   a link's columns are `link.ColumnSet`, its alias `link.EntityAlias`, its conditions `link.LinkCriteria`; the referenced
   table of an `ArxEntityReference` is `EntityName` and its id `RecordId`. `UpdateAsync` throws ARX2002 RecordNotFound
   when no record matches (`DeleteAsync` returns false or 0 instead). A page's `TotalRecordCount` is an `int`; an aggregate
   Count is a `long`. On DynamoDB a declared lookup reads back without its display name (`Name` is null: no joins).
16. **Ids and linked columns are plain values.** `entity.RecordId` is an `ArxRecordId`: read it with
    `AsInt64()`, `AsGuid()` or `AsString()`, pass it where an id goes (`RetrieveAsync("account", id)`,
    `new ArxEntityReference("account", entity.RecordId!)`), or pass the plain value instead. `ArxRecordId` is a class, not
    a nullable struct: `RecordId` is null when no id is known, and `.Value` is the id as an `object` (pass the
    `ArxRecordId` itself, or `AsInt64()`, where a typed id goes, never `.Value`). DynamoDB has no joins (ARX8001): read related items with their own query. Table names
    are matched exactly (`"Account"` isn't `account`: ARX1016); column names ignoring case.


## Packages and setup

- .NET: .NET SDK 10.0.100 or later 10.0.x (target `net10.0`); database: Amazon DynamoDB, or DynamoDB Local for development (tested with DynamoDB Local 2.5.2); driver: AWSSDK.DynamoDBv2 4.0.110 or later (the lowest version, which the provider is built on; Versions and compatibility lists the versions it is tested on).
- `ARX.SDK.DynamoDb` 1.0.0-rc.1: The Amazon DynamoDB provider. It brings ARX.SDK and AWSSDK.DynamoDBv2 4.0.110 with it. Install: `dotnet add package ARX.SDK.DynamoDb --version 1.0.0-rc.1`.
- The samples read the connection string from the `ARX_SAMPLES_DYNAMODB` environment variable, for example `http://localhost:8000`. Never put real credentials in code.

## Quick reference

The first scenario of each operation's first sample: verified code.

### Create: Create one record, in either design, A table of its own

In scope: `client` (IAmazonDynamoDB).

```csharp
var model = ArxDynamoModel.Create()
    .Table("product", partitionKey: "sku")
    .Build();

var service = new ArxDynamoDbService(client, model);

var product = new ArxEntity("product");
product["sku"] = "SKU-D101";
product["name"] = "Trail running shoe";
product["price"] = 129.90m;

await service.CreateAsync(product);

Console.WriteLine("created product SKU-D101");
```

### CreateMultiple: Create many records in one call, All stored together

In scope: `service` (ArxDynamoDbService).

```csharp
IReadOnlyList<ArxRecordId> ids = await service.CreateMultipleAsync(new[]
{
    Product("SKU-D201", "Rain jacket"),
    Product("SKU-D202", "Fleece"),
    Product("SKU-D203", "Beanie")
});

Console.WriteLine($"created {string.Join(", ", ids.Select(x => x.AsString()))}");
```

Defined in the sample, used above:

```csharp
private static ArxEntity Product(string sku, string name)
{
    var product = new ArxEntity("product");
    product["sku"] = sku;
    product["name"] = name;
    return product;
}
```

### Update: Update one record, By the id Create returned

In scope: `service` (ArxDynamoDbService), `id` (ArxRecordId).

```csharp
var change = new ArxEntity("product") { RecordId = id };
change["price"] = 79.00m;

int changed = await service.UpdateAsync(change);

Console.WriteLine($"{changed} item changed");
```

### UpdateMultiple: Update many records in one call, A price per product

In scope: `service` (ArxDynamoDbService), `ids` (IReadOnlyList<ArxRecordId>).

```csharp
var changes = new List<ArxEntity>();

for (var i = 0; i < ids.Count; i++)
{
    var change = new ArxEntity("product") { RecordId = ids[i] };
    change["price"] = 10.00m + i;
    changes.Add(change);
}

int changed = await service.UpdateMultipleAsync(changes);

Console.WriteLine($"{changed} items changed in one call");
```

### Delete: Delete one record, By the id Create returned

In scope: `service` (ArxDynamoDbService), `id` (ArxRecordId).

```csharp
bool deleted = await service.DeleteAsync("product", id);

Console.WriteLine($"deleted: {deleted}");
```

### DeleteMultiple: Delete many records in one call, Several ids at once

In scope: `service` (ArxDynamoDbService).

```csharp
int deleted = await service.DeleteMultipleAsync("product", new[] { "SKU-D302", "SKU-D303", "SKU-D399" });

Console.WriteLine($"{deleted} items deleted");
```

### Retrieve: Retrieve one record, By id

In scope: `service` (ArxDynamoDbService).

```csharp
ArxEntity? found = await service.RetrieveAsync("product", "SKU-D401");

Console.WriteLine($"{found!["name"]}, {found["price"]}");
```

### RetrieveMultiple: Retrieve many records, A customer's orders

In scope: `service` (ArxDynamoDbService).

```csharp
var query = new ArxQueryExpression("sales_order");
query.ColumnSet.AddColumns("order_number", "total");
query.Criteria.AddCondition("customer_id", ArxConditionOperator.Equal, "C-D411");
query.Criteria.AddCondition("status", ArxConditionOperator.Equal, "OPEN");
query.AddOrder("order_number", ArxOrderType.Descending);

var found = await service.RetrieveMultipleAsync(query);

Console.WriteLine(string.Join(", ", found.Entities.Select(x => $"{x["order_number"]} {x["total"]}")));
```

## The other files

- `arx-dynamodb-types.md`: Every public type: its declaration, constructors, properties, methods and their parameters, with what each does.
- `arx-dynamodb-sample-application.md`: The files the samples build on (the schema catalog, dbContext and its Service, the output helpers): what the samples' code refers to that isn't in the packages.
- `arx-dynamodb-data-types.md`: What each .NET type is stored as in Amazon DynamoDB, the date and time rules, and what each Amazon DynamoDB type reads back as.
- `arx-dynamodb-error-codes.md`: Every ARX error code: what it means, whether it is safe to retry, and the Amazon DynamoDB errors it comes from.
- `arx-dynamodb-create.md`: What a create does, its rules, and every Create sample: each scenario's code and the PartiQL statement that checks it.
- `arx-dynamodb-create-multiple.md`: What a CreateMultiple does, its rules, and every CreateMultiple sample: each scenario's code and the PartiQL statement that checks it.
- `arx-dynamodb-update.md`: What an update does, its rules, and every Update sample: each scenario's code and the PartiQL statement that checks it.
- `arx-dynamodb-update-multiple.md`: What an UpdateMultiple does, its rules, and every UpdateMultiple sample: each scenario's code and the PartiQL statement that checks it.
- `arx-dynamodb-delete.md`: What a delete does, its rules, and every Delete sample: each scenario's code and the PartiQL statement that checks it.
- `arx-dynamodb-delete-multiple.md`: What a DeleteMultiple does, its rules, and every DeleteMultiple sample: each scenario's code and the PartiQL statement that checks it.
- `arx-dynamodb-retrieve.md`: What a retrieve does, its rules, and every Retrieve sample: each scenario's code and the PartiQL statement that checks it.
- `arx-dynamodb-retrieve-multiple.md`: What a RetrieveMultiple does, its rules, and every RetrieveMultiple sample: each scenario's code and the PartiQL statement that checks it.
- `arx-dynamodb-benchmarks.md`: How ARX compares with the low-level AWS client, DynamoDBContext and BatchWriteItem, measured: the only source for performance claims.
- `arx-dynamodb-all.md`: everything in one file.
