c# - 如何将字符串列表从 Sql 数据插入到 Document Db/cosmos db 中?

标签 c# azure-cosmosdb azure-cosmosdb-sqlapi

我有 sql 数据库表并正在执行 select query 我正在获取数据并想将该数据插入到文档数据库中。

我试过如下 -

 private const string EndpointUrl = "<your endpoint URL>";
        private const string PrimaryKey = "<your primary key>";
        private DocumentClient client;

        private async Task InsertIntoDocuemntDb()
        {
            this.client = new DocumentClient(new Uri(EndpointUrl), PrimaryKey);

            await this.client.CreateDatabaseIfNotExistsAsync(new Database { Id = "FamilyDB" });

            await this.client.CreateDocumentCollectionIfNotExistsAsync(UriFactory.CreateDatabaseUri("FamilyDB"), new DocumentCollection { Id = "FamilyCollection" });


        }

我可以使用下面的代码获取 sql 数据 -

using (SqlConnection connection = new SqlConnection(ConnectionString))
            {
                connection.Open();
                SqlCommand cmd = new SqlCommand("select name , rollId from demotable ", connection);
                cmd.CommandType = CommandType.Text;

                using (SqlDataReader reader = cmd.ExecuteReader())
                {
                    while (reader.Read())

如何插入字符串列表并插入文档数据库?

最佳答案

我们可以使用 Microsoft Azure Document API 来实现这一点。

我们可以将数据插入到 cosmos db(Document) 中,如下所示:

public static async void InsertDoc(DocumentClient client, string collectionLink, Document doc)
    {
        Document created = await client.CreateDocumentAsync(collectionLink, doc);
    }

在您的代码中,我们可以执行以下操作:

        using (SqlConnection connection = new SqlConnection(ConnectionString))
        {
            connection.Open();
            SqlCommand cmd = new SqlCommand("select name , rollId from demotable ", connection);
            cmd.CommandType = CommandType.Text;

            using (SqlDataReader reader = cmd.ExecuteReader())
            {
                while (reader.Read()){
                   dynamic document = new Document();
                   document.name = reader["name"].ToString(); 
                   document.rollId = reader["rollId"].ToString();
                   InsertDoc(client, UriFactory.CreateDocumentCollectionUri("FamilyDB", "FamilyCollection"), document);
                }
            }

        }

更多关于Azure Document API的信息,我们可以引用:Document API

关于c# - 如何将字符串列表从 Sql 数据插入到 Document Db/cosmos db 中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51036592/

相关文章:

Azure Cosmos DB 日志和诊断设置

c# - 无法翻译 LINQ 表达式 DbSet<>.Any

python - 如何使用Python将批量数据插入Cosmos DB?

c# - CosmosDb SDK v3 是否在批量插入时自动重试?

c# - File.SetAttributes() 无法按预期在 USB key 上工作

azure - 如何使用 Azure 云函数从 CosmosDB 中删除文档?

c# - 如何在 C# 中获取 HTTP Post 数据 - FiddlerCore?

azure - CosmosDB + 分组依据

c# - 从麦克风实时播放音频。 C#

c# - 反序列化接口(interface)集合时,使用自定义转换器从以前的数据模型反序列化 JSON 失败