创建文档

已完成

要创建一个新项,需要先在 Product 类型的 C# 代码中创建一个新变量

Product saddle = new()
{
    id = "027D0B9A-F9D9-4C96-8213-C8546C4AAE71",
    categoryId = "26C74104-40BC-4541-8EF5-9892F7F03D72",
    name = "LL Road Seat/Saddle",
    price = 27.12d,
    tags = new string[] 
    {
        "brown",
        "weathered"
    }
};

现在推断已有一个 Microsoft.Azure.Cosmos.Container 类型的变量,名为 container

可以异步调用 CreateItemAsync<> 方法,将泛型 Product 类型和新变量项传递到构造函数中。

await container.CreateItemAsync<Product>(saddle);

此方法调用将创建新项,但不会得到任何有关操作结果的元数据。 也可以将操作结果存储在类型为 ItemResponse<> 的变量中。

ItemResponse<Product> response = await container.CreateItemAsync<Product>(saddle);

HttpStatusCode status = response.StatusCode;
double requestUnits = response.RequestCharge;

Product item = response.Resource;

如果使用的是 try-catch 块,可以处理 CosmosException 类型,该类型包括作为 HTTP 状态码值的 StatusCode 属性。 应考虑在应用程序代码中使用一些常见的 HTTP 状态代码:

代码 标题 原因
400 无效的请求 请求正文中的项有问题
403 已禁止 容器可能已满
409 Conflict 容器中的项可能已有匹配的 ID
413 RequestEntityTooLarge 项大小超过最大实体大小
429 TooManyRequests 当前请求超出了为容器预配的最大 RU/秒

在本示例中

try
{
    await container.CreateItemAsync<Product>(saddle);
}
catch(CosmosException ex) when (ex.StatusCode == HttpStatusCode.Conflict)
{
    // Add logic to handle conflicting ids
}
catch(CosmosException ex) 
{
    // Add general exception handling logic
}