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

时间:2018-06-26 06:54:30

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

我有sql数据库表,正在做 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" }); } ,我正在获取数据,并希望将该数据插入到文档db中。

我尝试如下-

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

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

value

如何插入字符串列表并插入到文档db中?

1 个答案:

答案 0 :(得分:2)

我们可以使用Microsoft Azure文档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文档API的更多信息,我们可以参考:Document API