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

How to insert list of string into Document Db / cosmos db from Sql data?

我有 sql 数据库 table 正在做 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