【问题标题】:How to insert list of string into Document Db / cosmos db from Sql data?如何将字符串列表从 Sql 数据插入 Document Db / cosmos db?
【发布时间】:2018-06-26 06:54:30
【问题描述】:

我有 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())

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

【问题讨论】:

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


    【解决方案1】:

    我们可以使用 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

    【讨论】:

    • 我所做的是我把 list 传递给 CreateDocumentAsync 得到错误 - 对象序列化为数组。预期的 JObject 实例,任何解决方案?
    • 我不想一个一个地去我想要一份带有项目列表的文档
    • 要插入多条数据,我们可以使用批量执行库:github.com/Azure/…
    • 我们也可以参考这个帖子:stackoverflow.com/questions/36063169/…
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-01-03
    • 1970-01-01
    • 1970-01-01
    • 2018-10-21
    • 2017-06-13
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多