首页 > 解决方案 > 抛出异常:“Microsoft.Azure.Cosmos.CosmosException”,将 JSON 批量导入 Azure Cosmos DB 时出现错误请求

问题描述

我正在尝试将JSON包含列表的文件JSONs从 .Net 4.6.1 控制台应用程序批量导入到 Azure Cosmos DB。

我成功地创建了数据库和容器。但是,我在第 40 行收到以下错误,并且没有创建项目。错误 :

DocDBTrace 错误:0:不会重试操作。当前尝试 0,状态代码:BadRequest 抛出异常:Microsoft.Azure.Cosmos.Client.dll 中的“Microsoft.Azure.Cosmos.CosmosException”抛出异常:mscorlib.dll 中的“System.AggregateException”

示例代码:

class Program
{

private static string EndpointUrl = $"";
private const string AuthorizationKey = "";
private const string DatabaseName = "TestDB";
private const string ContainerName = "BulkImportTest";
public static async Task Main(string[] args)
{
    string json = File.ReadAllText(@"BulkImport.json");

    List<StudentInfo> lists = JsonConvert.DeserializeObject<List<StudentInfo>>(json);

    CosmosClientOptions options = new CosmosClientOptions() { ConnectionMode = ConnectionMode.Gateway, AllowBulkExecution = true };
    CosmosClient cosmosClient = new CosmosClient(EndpointUrl, AuthorizationKey, options);

    try
    {
        Database database = await cosmosClient.CreateDatabaseIfNotExistsAsync(DatabaseName);
        Console.WriteLine(database.Id);
        Container container = await database.CreateContainerIfNotExistsAsync(ContainerName, "/SId");
        Console.WriteLine(container.Id);
        List<Task> tasks = new List<Task>();
        foreach (StudentInfo item in lists)
        {
                tasks.Add(container.CreateItemAsync(item, new PartitionKey(item.SId)));
        }
        await Task.WhenAll(tasks); // Line 40
        }

    catch(Exception ex)
    {
            Console.WriteLine("Exception = " + ex.Message);
    }


    Console.ReadLine();
}
    class StudentInfo
    {
        public string SId { get; set; }
        public string SName { get; set; }
    }}

BulkImport.json :

  [
  {
    "SId": "101",
    "SName": "ABC",
  },
  {
    "SId": "102",
    "SName": "XYZ",
  }
  ]

请帮助我解决这个问题。

进行建议的更新后,我仍然面临类似的问题:

DocDBTrace 错误:0:不会重试操作。当前尝试 0,状态代码:BadRequest 抛出异常:Microsoft.Azure.Cosmos.Client.dll 中的“Microsoft.Azure.Cosmos.CosmosException”抛出异常:mscorlib.dll 中的“Microsoft.Azure.Cosmos.CosmosException”

标签: c#.netazure-cosmosdb

解决方案


根据我的测试,当我们创建一个新文档时,我们必须提供“id”属性。更多详细信息,请参阅文档

例如

我的.json档案

 [{
         "SId": "101",
         "SName": "ABC"
     }, {
         "SId": "102",
         "SName": "XYZ"
     }
 ]

我的代码

        async static Task Main(string[] args)
        {
            string json = File.ReadAllText(@"E:\test.json");
            List<StudentInfo> lists = JsonConvert.DeserializeObject<List<StudentInfo>>(json);            
            CosmosClientOptions options = new CosmosClientOptions() { AllowBulkExecution = true, ConnectionMode = ConnectionMode.Gateway };
            CosmosClient cosmosClient = new CosmosClient(EndpointUrl, AuthorizationKey, options);
            Database database = await cosmosClient.CreateDatabaseIfNotExistsAsync(DatabaseName);
            Console.WriteLine(database.Id);
            Container container = await database.CreateContainerIfNotExistsAsync(ContainerName,"/SId");
            Console.WriteLine(container.Id);
            List<Task> tasks = new List<Task>();
            foreach (StudentInfo item in lists)
            {
                item.Id = Guid.NewGuid().ToString();// add the line in your code
                tasks.Add(container.CreateItemAsync(item, new PartitionKey(item.SId))
                    .ContinueWith((Task<ItemResponse<StudentInfo>> task) =>
                    {
                        Console.WriteLine("Status: " + task.Result.StatusCode + "    Resource: " + task.Result.Resource.SId);
                    }));
            }
            await Task.WhenAll(tasks);
            Console.ReadLine();
        }
        class StudentInfo
        {            
            public string SId { get; set; }
            public string SName { get; set; }
            [JsonProperty(PropertyName = "id")]// add the code in your custom object
            public string Id { get; set; }//add the code in your custom object

        }
    }

在此处输入图像描述


推荐阅读