你当前正在访问 Microsoft Azure Global Edition 技术文档网站。 如果需要访问由世纪互联运营的 Microsoft Azure 中国技术文档网站,请访问 https://docs.azure.cn

使用 .NET 在 Azure Cosmos DB for NoSQL 中创建项

Azure Cosmos DB 中的项表示存储在容器中的特定实体。 在 API for NoSQL 中,项由具有唯一标识符的 JSON 格式数据组成。

为项创建唯一标识符

唯一标识符是标识容器中的项的非重复字符串。 该 id 属性是创建新 JSON 文档时唯一必需的属性。 例如,此 JSON 文档是 Azure Cosmos DB 中的有效项:

{
  "id": "unique-string-2309509"
}

在容器的范围内,两个项不能共享相同的唯一标识符。

重要

id 属性区分大小写。 名为 IDIdiD_id 将被视为任意 JSON 属性的属性。

创建后,项的 URI 采用以下格式:

https://<cosmos-account-name>.documents.azure.com/dbs/<database-name>/docs/<item-resource-identifier>

使用 URI 引用项时,请使用系统生成的 资源标识符 而不是 id 字段。 有关 Azure Cosmos DB for NoSQL 中系统生成的项属性的详细信息,请参阅 项的属性

创建一个项目

注释

本文中的示例假定你已定义一个 C# 类型来表示名为 Product 的数据:

// C# record type for items in the container
public record Product(
    string id,
    string category,
    string name,
    int quantity,
    bool sale
);

这些示例还假定你已经创建了名为 newItem的 Product 类型的新对象:

// Create new item and add to container
Product item = new(
    id: "68719518388",
    category: "gear-surf-surfboards",
    name: "Sunnox Surfboard",
    quantity: 8,
    sale: true
);

若要创建项,请调用以下方法之一:

异步创建项目

以下示例以异步方式创建新项:

Product createdItem = await container.CreateItemAsync<Product>(
    item: item,
    partitionKey: new PartitionKey("gear-surf-surfboards")
);

如果存在与现有项的唯一标识符冲突,该方法 Container.CreateItemAsync<> 将引发异常。 若要了解有关潜在异常的详细信息,请参阅 CreateItemAsync<> 异常

异步替换一个项目

以下示例异步替换现有项:

Product replacedItem = await container.ReplaceItemAsync<Product>(
    item: item,
    id: "68719518388",
    partitionKey: new PartitionKey("gear-surf-surfboards")
);

该方法 Container.ReplaceItemAsync<> 要求为参数提供字符串 id 以匹配参数的唯一标识符 item

异步创建或替换一个项

以下示例将创建新项,如果项已存在,则使用相同的唯一标识符替换现有项:

Product upsertedItem = await container.UpsertItemAsync<Product>(
    item: item,
    partitionKey: new PartitionKey("gear-surf-surfboards")
);

该方法 Container.UpsertItemAsync<> 将使用参数的唯一标识符 item 来确定是否存在与现有项冲突并相应地替换项。

后续步骤

现在你已创建各种项,请使用下一个指南读取项。