首页 > 解决方案 > 通过 DTUI 将 JSON 文档加载到 Azure CosmosDB 中,如何批量转换文档以便使用 LINQ 进行查询?

问题描述

我使用 DTUI 实用程序将几千个 JSON 文档批量加载到 CosmosDB 中。

从那以后,我从所述 JSON 文档中对 C# 对象模型进行了逆向工程。

我正在尝试使用我的 C# 类型查询 LINQ 中的集合,我假设这是因为一切都只是一个 CosmosDB 文档。

无论如何转换/映射我的集合中的所有文档,以便它们被识别为我的 C# 类型?

标签: azure-cosmosdb

解决方案


无论如何转换/映射我的集合中的所有文档,以便它们被识别为我的 C# 类型?

这是 SDK 为您处理的事情。正如您所提到的,存储在 Cosmos DB 中的文档是 JSON 格式的。您需要做的是在您的代码中创建等效的类,SDK 会使用 JSON 序列化将文档映射到您的 C# 类。

例如,假设我在 Cosmos DB 中有以下文档:

{
    "id": "bcd1f574e8f94034fed7c245130c2b65",
    "firstName": "Gaurav",
    "lastName": "Mantri"
}

我需要做的是创建一个映射到该文档的模型。就像是:

using Newtonsoft.Json;

public class User
{
    [JsonProperty(PropertyName = "id")]
    public string Id { get; set; }
    
    [JsonProperty(PropertyName = "firstName")]
    public string FirstName { get; set; }
    
    [JsonProperty(PropertyName = "lastName")]
    public string LastName { get; set; }
}

当我查询我的容器时,我会指示 SDK 将文档映射到这个模型。类似于以下内容:

FeedIterator<User> resultSetIterator = container.GetItemQueryIterator<User>("Select * from root r where r.id = 'bcd1f574e8f94034fed7c245130c2b65'");
while (resultSetIterator.HasMoreResults)
{
    FeedResponse<User> users = await resultSetIterator.ReadNextAsync();
    foreach (User user in users)
    {
        Console.WriteLine($"User id: {user.Id}");
        Console.WriteLine($"Name: {user.FirstName} {user.LastName}");
    }
}

上面的代码将在控制台上打印以下内容:

User id: bcd1f574e8f94034fed7c245130c2b65
Name: Gaurav Mantri

这是完整的代码:

using System;
using System.Threading.Tasks;
using Microsoft.Azure.Cosmos;
using Newtonsoft.Json;

namespace CosmosDbSQLAPISamples
{
    class Program
    {
        private static string connectionString = "connection-string";

        private static string databaseId = "database-name";
        private static string containerId = "container-name";

        static async Task Main(string[] args)
        {
            CosmosClient client = new CosmosClient(connectionString);
            Container container = client.GetContainer(databaseId, containerId);
            FeedIterator<User> resultSetIterator = container.GetItemQueryIterator<User>("Select * from root r where r.id = 'bcd1f574e8f94034fed7c245130c2b65'");
            while (resultSetIterator.HasMoreResults)
            {
                FeedResponse<User> users = await resultSetIterator.ReadNextAsync();
                foreach (User user in users)
                {
                    Console.WriteLine($"User id: {user.Id}");
                    Console.WriteLine($"Name: {user.FirstName} {user.LastName}");
                }
            }
        }
    }

    public class User
    {
        [JsonProperty(PropertyName = "id")]
        public string Id { get; set; }
        
        [JsonProperty(PropertyName = "firstName")]
        public string FirstName { get; set; }
        
        [JsonProperty(PropertyName = "lastName")]
        public string LastName { get; set; }
    }
}

推荐阅读