建立資料庫(.NET)
你可以使用 DocumentClient
類的 CreateDatabaseAsync
方法建立 DocumentDB 資料庫。資料庫是跨集合分割槽的 JSON 文件儲存的邏輯容器。
using System.Net;
using System.Threading.Tasks;
using Microsoft.Azure.Documents;
using Microsoft.Azure.Documents.Client;
要建立資料庫:
async Task CreateDatabase(DocumentClient client)
{
var databaseName = "<your database name>";
await client.CreateDatabaseAsync(new Database { Id = databaseName });
}
你還可以檢查資料庫是否已存在,並在需要時建立它:
async Task CreateDatabaseIfNotExists(DocumentClient client)
{
var databaseName = "<your database name>";
try
{
await client.ReadDatabaseAsync(UriFactory.CreateDatabaseUri(databaseName));
}
catch (DocumentClientException e)
{
// If the database does not exist, create a new database
if (e.StatusCode == HttpStatusCode.NotFound)
{
await client.CreateDatabaseAsync(new Database { Id = databaseName });
}
else
{
// Rethrow
throw;
}
}
}