C# 如何从Sql数据将字符串列表插入文档Db/cosmos Db?
我有一个sql数据库表,正在执行C# 如何从Sql数据将字符串列表插入文档Db/cosmos Db?,c#,azure-cosmosdb,azure-cosmosdb-sqlapi,C#,Azure Cosmosdb,Azure Cosmosdb Sqlapi,我有一个sql数据库表,正在执行selectquery操作,我正在获取数据,并希望将该数据插入到文档数据库中 我试过如下- private const string EndpointUrl = "<your endpoint URL>"; private const string PrimaryKey = "<your primary key>"; private DocumentClient client; priva
selectquery
操作,我正在获取数据,并希望将该数据插入到文档数据库中
我试过如下-
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" });
}
如何插入字符串列表并插入文档数据库?我们可以使用Microsoft Azure文档API来实现这一点 我们可以按如下方式将数据插入cosmos db(文档):
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);
}
}
}
在您的代码中,我们可以执行以下操作:
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的更多信息,我们可以参考:我所做的是获取列表并将其传递给CreateDocumentSync获取错误-对象序列化到数组。需要JObject实例,有解决方案吗?我不想一个接一个地去我想要一个带有项目列表的文档要插入多个数据,我们可以使用批量执行器库:我们也可以参考此线程: