本文代码摘自cosmosdb官网,然后仿照着自己添加了一个删除container的函数,记录在此以便查阅。
想自行尝试的话可以去Home - Microsoft Azure官网按照教程操作一遍,会自动下载一个项目到本地,然后自己跑跑就好了:
其实核心思路就是:
- 首先创建一个用于连接azure cosmosdb的cosmosclient实例
- 然后就利用cosmosclient上提供的API进行各种操作
常用的操作包含下如下几个函数里,可以自行查看:
CreateDatabaseAsync(); // 创建database
CreateContainerAsync(); // 创建container,可以理解为创建表
ScaleContainerAsync(); // 设置吞吐量
AddItemsToContainerAsync(); // 插入一条记录
QueryItemsAsync(); // 查询一条记录
ReplaceFamilyItemAsync(); // 修改
DeleteFamilyItemAsync(); // 删除
DeleteContainerAndCleanupAsync(); // 删除container
DeleteDatabaseAndCleanupAsync(); // 删除数据库
完整代码:
using System;
using System.Threading.Tasks;
using System.Configuration;
using System.Collections.Generic;
using System.Net;
using Microsoft.Azure.Cosmos;
namespace CosmosGettingStartedTutorial
{
class Program
{
// The Azure Cosmos DB endpoint for running this sample.
private static readonly string EndpointUri = ConfigurationManager.AppSettings["EndPointUri"];
// The primary key for the Azure Cosmos account.
private static readonly string PrimaryKey = ConfigurationManager.AppSettings["PrimaryKey"];
// The Cosmos client instance
private CosmosClient cosmosClient;
// The database we will create
private Database database;
// The container we will create.
private Container container;
// The name of the database and container we will create
private string databaseId = "ToDoList";
private string containerId = "Items";
// <Main>
public static async Task Main(string[] args)
{
try
{
Console.WriteLine("Beginning operations...\n");
Program p = new Program();
await p.GetStartedDemoAsync();
}
catch (CosmosException de)
{
Exception baseException = de.GetBaseException();
Console.WriteLine("{0} error occurred: {1}", de.StatusCode, de);
}
catch (Exception e)
{
Console.WriteLine("Error: {0}", e);
}
finally
{
Console.WriteLine("End of demo, press any key to exit.");
Console.ReadKey();
}
}
// </Main>
// <GetStartedDemoAsync>
/// <summary>
/// Entry point to call methods that operate on Azure Cosmos DB resources in this sample
/// </summary>
public async Task GetStartedDemoAsync()
{
// Create a new instance of the Cosmos Client
this.cosmosClient = new CosmosClient(EndpointUri, PrimaryKey, new CosmosClientOptions() { ApplicationName = &#