練習 - 建立適用於 NoSQL 的 API 帳戶和資源
現在您可以建立將在 Azure Cosmos DB 帳戶中使用的各種資源,例如資料庫、容器和項目。 在本練習中,您會使用名為 products
的單一容器,建立名為 cosmicworks
的資料庫。 如果您多次執行此主控台應用程式,您必須確定程式碼不會當機而嘗試重新建立容器。
現在,您有幾個主要需求:
- 如果資料庫不存在,請建立資料庫
- 如果容器不存在,請建立容器
完成此練習之後,您的專案將會建立任何資料庫,或執行所需的容器。
建立資料庫
SDK 包含實用的方法,會在資源不存在時建立新的資源。 藉由使用這些方法,您可以多次執行應用程式,而不必擔心衝突所引發的例外狀況。 在這裡,您會建立資料庫。
返回 Program.cs 檔案。
呼叫 CreateDatabaseIfNotExistsAsync(String, ThroughputProperties, RequestOptions, CancellationToken) 來建立或取得新的資料庫。 將結果儲存在名為
database
的變數中。 請務必設定這些參數:參數 值 id cosmicworks
Database database = await client.CreateDatabaseIfNotExistsAsync( id: "cosmicworks" );
輸出資料庫的唯一識別碼。
Console.WriteLine($"[Database created]:\t{database.Id}");
儲存Program.cs 檔案。
建立容器
在這裡,您會建立容器,其中包含資料庫中共用輸送量的特定「配量」。
使用 ContainerProperties 型別建立新容器的屬性物件。 將結果儲存在名為
properties
的變數中。 請務必設定這些參數:參數 值 id products
partitionKeyPath /categoryId
ContainerProperties properties = new( id: "products", partitionKeyPath: "/categoryId" );
使用CreateAutoscaleThroughput(Int32)靜態方法建立自動調整輸送量物件。 將結果儲存在名為
throughput
的變數中。 請務必設定這些參數:參數 值 autoscaleMaxThroughput 1000
var throughput = ThroughputProperties.CreateAutoscaleThroughput( autoscaleMaxThroughput: 1000 );
呼叫 CreateContainerIfNotExistsAsync(String, String, Nullable<Int32>, RequestOptions, CancellationToken) 來建立或取得新的容器。 將結果儲存在名為
container
的變數中。 請務必設定這些參數:Container container = await database.CreateContainerIfNotExistsAsync( containerProperties: properties, throughputProperties: throughput );
現在,輸出容器的唯一識別碼。
Console.WriteLine($"[Container created]:\t{container.Id}");
儲存Program.cs 檔案。
建立項目的記錄類型
C# 資料可以使用各種類型來表示,包括類別、結構及記錄。 針對此 SDK,記錄會很有用,因為其預設為不可變。 如果您需要,您仍然可以新增程式碼來建立記錄的修改複本。 記錄也有容易閱讀的語法,而且只需要幾行程式碼就能快速建立。 在本節中,您會為所有項目,以及每個「種類」項目的個別類型建立基底類型。
使用 Visual Studio Code 建立名為 Item.cs 的新檔案。 然後在編輯器中開啟檔案。
建立名為
Item
的基礎記錄類型,其中包含您要在此容器的所有項目中使用之三個屬性:id
、categoryId
和type
。public record Item( string Id, string CategoryId, string Type );
儲存Item.cs 檔案。 關閉 Item.cs 檔案。
建立另一個名為 Category.cs 的新檔案。 現在在編輯器中開啟此檔案。
建立名為 Category 的新類型,此類型繼承自 Item 類型。 請確定類型會將其值傳遞至基底實作,並將 type 變數設定為輸出 Category 類型的名稱。
public record Category( string Id, string CategoryId ) : Item( Id, CategoryId, nameof(Category) );
儲存Category.cs 檔案。 關閉 Category.cs 檔案。
最後,建立名為 Product.cs 的最後一個檔案。 也在編輯器中開啟此檔案。
建立名為 Product 的新類型,其繼承自 Item,並新增一些新屬性:
name
、price
、archived
和quantity
。public record Product( string Id, string CategoryId ) : Item( Id, CategoryId, nameof(Product) ) { public string Name { get; init; } = default!; public decimal Price { get; init; } public bool Archived { get; init; } public int Quantity { get; init; } };
儲存Product.cs 檔案。 關閉 Product.cs 檔案。
檢查您的工作
您的應用程式現在會建立資料庫和容器。 您用來建立這些資源的方法具有足夠的復原性,足以執行多次,而不會造成例外狀況。 在這裡,您會執行應用程式,並檢查兩個資源的唯一識別碼輸出。
在終端機中執行 .NET 應用程式
dotnet run
觀察執行應用程式的輸出。 輸出應該會與此處範例相符:
... [Database created]: cosmicworks [Container created]: products