이 문서에는 Windows 앱에서 Cosmos DB 데이터베이스 작업을 사용하도록 설정하는 데 필요한 단계가 포함되어 있습니다. 코드로 데이터베이스와 상호 작용하는 방법을 보여주는 작은 코드 조각도 포함되어 있습니다.
솔루션 설정
이 예제는 WPF, Windows Forms 및 WinUI 프로젝트와 함께 사용하여 Windows 앱을 Cosmos DB 데이터베이스에 연결할 수 있습니다. 다음 단계에 따라 패키지를 설치하고 몇 가지 기본 작업에 대한 코드 예제를 사용해 보세요.
-
Package Manager 콘솔(-> 기타 Windows -> Package Manager 콘솔 보기)을 엽니다. 명령
Install-Package Microsoft.Azure.Cosmos을 사용하여 .NET용 Azure Cosmos DB for NoSQL 클라이언트 라이브러리의 NuGet 패키지를 설치합니다. 이렇게 하면 프로그래밍 방식으로 Cosmos DB 데이터베이스에 액세스할 수 있습니다. - 프로젝트를 빌드하고 오류 없이 빌드가 성공했는지 확인합니다.
다음으로, Azure Cosmos DB 인스턴스를 만들어야 합니다. 이 작업은
샘플 코드를 사용하여 Cosmos DB 작업
다음 샘플 코드는 Azure Cosmos DB 인스턴스에서 컨테이너를 가져오고 해당 컨테이너에 새 항목을 추가합니다. 그런 다음 Cosmos DB의 NoSQL 쿼리 API를 사용하여 컨테이너에서 항목을 검색하고 응답 상태를 출력합니다. 엔드포인트, 인증 키 및 데이터베이스 이름은 이전 섹션에서 만든 Cosmos DB 인스턴스를 기반으로 사용자 지정해야 합니다.
참고
필요한 Cosmos DB 설정 및 구성에 대한 정보를 포함하는 전체 예제는
using Microsoft.Azure.Cosmos;
...
public async Task CosmosSample(string endpoint, string authKey)
{
// CONNECT
var client = new CosmosClient(
accountEndpoint: endpoint,
authKeyOrResourceToken: authKey
);
Database database = client.GetDatabase("sample_customers");
ContainerProperties properties = new(
id: "customers",
partitionKeyPath: "/location"
);
Container container = await database.CreateContainerIfNotExistsAsync(properties);
// WRITE DATA
string customerId = "1234";
string state = "WA";
var customer = new
{
id = customerId,
name = "John Doe",
location = state
};
var createResponse = await container.CreateItemAsync(customer);
Console.WriteLine($"[Status code: {createResponse.StatusCode}]\t{customerId}");
// READ DATA
string sql = "SELECT * FROM customers c WHERE c.id = @id";
var query = new QueryDefinition(
query: sql
).WithParameter("@id", customerId);
using var feed = container.GetItemQueryIterator<dynamic>(queryDefinition: query);
var queryResponse = await feed.ReadNextAsync();
Console.WriteLine($"[Status code: {queryResponse.StatusCode}]\t{customerId}");
}
관련 콘텐츠
GitHub에서 Microsoft와 공동 작업
이 콘텐츠의 원본은 GitHub에서 찾을 수 있으며, 여기서 문제와 끌어오기 요청을 만들고 검토할 수도 있습니다. 자세한 내용은 참여자 가이드를 참조하세요.
Windows developer