Поиск  
Always will be ready notify the world about expectations as easy as possible: job change page
сегодня

Working with Azure Cosmos DB in .NET Core: A Step-by-Step Guide

Working with Azure Cosmos DB in .NET Core: A Step-by-Step Guide
Автор:
Источник:
Просмотров:
47

Azure Cosmos DB is a globally distributed, multi-model database service provided by Microsoft Azure. It supports multiple data models, including document, key-value, graph, and column-family data models. In this article, we’ll explore how to add and retrieve data from Azure Cosmos DB using .NET Core, focusing on the document model.

Prerequisites

Before you begin, ensure you have the following:

  1. An Azure account with access to Cosmos DB.
  2. A Cosmos DB account and a database with a container.

Setting up the .NET Core project

1. Create a new .NET Core Console App:

Open a terminal and run the following commands:

dotnet new console -n CosmosDbExample
cd CosmosDbExamplebash

2. Install Azure Cosmos DB SDK:

Install the Azure Cosmos DB SDK for .NET by running the following command:

dotnet add package Microsoft.Azure.Cosmos

Writing code to add and retrieve data

Now, let’s write code to interact with Azure Cosmos DB.

Add data

using Microsoft.Azure.Cosmos;
using System;
using System.Threading.Tasks;

class Program
{
    private const string EndpointUrl = "your_cosmos_db_endpoint";
    private const string PrimaryKey = "your_cosmos_db_primary_key";
    private const string DatabaseId = "YourDatabaseId";
    private const string ContainerId = "YourContainerId";

    static async Task Main(string[] args)
    {
        CosmosClient cosmosClient = new CosmosClient(EndpointUrl, PrimaryKey);
        Database database = await cosmosClient.CreateDatabaseIfNotExistsAsync(DatabaseId);
        Container container = await database.CreateContainerIfNotExistsAsync(ContainerId, "/PartitionKey");

        // Add data
        dynamic item = new
        {
            Id = Guid.NewGuid().ToString(),
            Name = "John Snow",
            Age = 30,
            PartitionKey = "PartitionKeyValue"
        };

        ItemResponse<dynamic> response = await container.CreateItemAsync(item, new PartitionKey(item.PartitionKey));
        Console.WriteLine($"Created item in database with id: {response.Resource.Id}");
    }
}

Replace `”your_cosmos_db_endpoint”`, `”your_cosmos_db_primary_key”`, `”YourDatabaseId”`, and `”YourContainerId”` with your Cosmos DB account details.

Retrieve data

using Microsoft.Azure.Cosmos;
using System;
using System.Linq;
using System.Threading.Tasks;

class Program
{
    private const string EndpointUrl = "your_cosmos_db_endpoint";
    private const string PrimaryKey = "your_cosmos_db_primary_key";
    private const string DatabaseId = "YourDatabaseId";
    private const string ContainerId = "YourContainerId";

    static async Task Main(string[] args)
    {
        CosmosClient cosmosClient = new CosmosClient(EndpointUrl, PrimaryKey);
        Database database = cosmosClient.GetDatabase(DatabaseId);
        Container container = database.GetContainer(ContainerId);

        // Retrieve data
        var query = new QueryDefinition("SELECT * FROM c WHERE c.Age > @age")
            .WithParameter("@age", 25);

        var iterator = container.GetItemQueryIterator<dynamic>(query);

        while (iterator.HasMoreResults)
        {
            FeedResponse<dynamic> response = await iterator.ReadNextAsync();
            foreach (var item in response)
            {
                Console.WriteLine($"Id: {item.Id}, Name: {item.Name}, Age: {item.Age}");
            }
        }
    }
}

Replace the same placeholders as in the previous example.

Final thoughts

In this article, we’ve walked through the process of adding and retrieving data from Azure Cosmos DB using .NET Core. Azure Cosmos DB provides a flexible and scalable solution for managing diverse data types, and the .NET SDK simplifies the development process.

Remember to handle sensitive information, such as connection strings and keys, securely in a production environment. Additionally, consider error handling and logging to make your application more robust.

By following these steps, you should be able to integrate Azure Cosmos DB into your .NET Core applications, allowing you to store and retrieve data efficiently.

Похожее
Jan 25
Author: Dev·edium
A deep dive into Ahead-of-Time (AOT) compilation for optimized performance What is it? Traditionally, .NET languages like C# use Just-in-Time (JIT) compilation. In this process, the source code is initially compiled into Common Intermediate Language (CIL) code, a platform-agnostic code...
Feb 18, 2023
Author: Adnan Puzic
Good UX design happens when you don’t notice it during or after the experience. The main goal of good UX design is to take the user on a specific mission as quickly as possible, with the least effort possible. In...
Apr 24, 2022
Author: Juan Alberto España Garcia
The security of .NET applications is necessary and knowing how to protect it is not always an easy task. As developers, we must be clear that an insecure application can be a serious problem: from modifying the operation of the...
Jul 18
Author: Vinod Pal
In today’s fast-paced business environment, efficiency and responsiveness are crucial for maintaining a competitive edge. Background batch processing plays a pivotal role in achieving these goals by handling time-consuming tasks asynchronously, thereby freeing up system resources and ensuring a seamless...
Написать сообщение
Почта
Имя
*Сообщение


© 1999–2024 WebDynamics
1980–... Sergey Drozdov
Area of interests: .NET Framework | .NET Core | C# | ASP.NET | Windows Forms | WPF | HTML5 | CSS3 | jQuery | AJAX | Angular | React | MS SQL Server | Transact-SQL | ADO.NET | Entity Framework | IIS | OOP | OOA | OOD | WCF | WPF | MSMQ | MVC | MVP | MVVM | Design Patterns | Enterprise Architecture | Scrum | Kanban