山本  洋介

山本 洋介

1643002920

Azure CosmosDBでCRUD操作を実行する

この記事では、EFCoreを使用してAzureCosmosDBでCRUD操作を実行できる.NET5APIを作成する方法を学習します。

前提条件 

  • Azureアカウント-まだお持ちでない場合は、クラウドコンピューティングサービス|にアクセスして無料で作成できます。MicrosoftAzure。
  • Azure Cosmos DBのセットアップ-その方法の詳細な手順が必要な場合は、この記事に従ってください

フォローするには、Azure Cosmos DBにVideogamesDBというデータベースと、Videogamesというコンテナーを作成してください。

ステップ1 

  1. VS 2019を開き、新しいASP .NET Core WebAPIを作成します。
  2. ターゲットフレームワークを.NET5として選択します。
  3. NuGetパッケージ「Microsoft.EntityFrameworkCore.Cosmos」バージョン5.0.1をインストールします

ステップ2-appsettings.jsonファイルを編集します

appsettings.jsonファイルを編集して、Azure Cosmos DBのアカウント、主キー、およびデータベース名を含める必要があります。次のコードをコピーしてappsettings.jsonファイルに貼り付けます

{
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft": "Warning",
      "Microsoft.Hosting.Lifetime": "Information"
    }
  },
  "CosmosDb": {
    "Account": "<>",
    "Key": "<>",
    "DatabaseName": "<>",
    "ContainerName": "<>"
  },
  "AllowedHosts": "*"
}

JavaScript

Azure Cosmos DBの「アカウント」の値をURIに、「キー」を主キーに置き換えます(下のスクリーンショットを参照)。

EFCoreを使用してAzureCosmos DB(SQL API)でCRUD操作を実行する.NET5アプリを作成します

DatabaseNameとContainerNameを、Azure Cosmos DBの[概要]セクションのデータベースとIDに置き換えます(下のスクリーンショットを参照)。

EFCoreを使用してAzureCosmos DB(SQL API)でCRUD操作を実行する.NET5アプリを作成します

ステップ3-DBコンテキストを作成する

DbContextは、データベースとのセッションを作成するために使用され、すべてのCRUD操作を実行するために使用されます。 

DBContextという名前の新しいフォルダーを作成し、その中に新しいクラスApplicationDbContextを追加します。次のコードをコピーしてApplicationDbContextに貼り付けます

using AzureCosmosEFCoreCRUD.Models;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Metadata.Builders;

namespace AzureCosmosEFCoreCRUD.DBContext
{
    public class ApplicationDbContext : DbContext
    {
        public ApplicationDbContext(DbContextOptions dbContextOptions) : base(dbContextOptions)
        {
        }
        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {

            modelBuilder.Entity<Videogames>()
                 .HasNoDiscriminator()
                 .ToContainer(nameof(Videogames))
                 .HasPartitionKey(da => da.Id)
                 .HasKey(da => new { da.Id });
            modelBuilder.ApplyConfiguration(new VideogameEntityConfiguration());

        }
        public DbSet<Videogames> Videogames { get; set; }
    }
    public class VideogameEntityConfiguration : IEntityTypeConfiguration<Videogames>
    {
        public void Configure(EntityTypeBuilder<Videogames> builder)
        {
           builder.OwnsOne(x => x.Company);
        }
    }

}

C#

ステップ4-モデルクラスを追加する

Modelsというフォルダを追加します。CompanyとVideogameの2つのモデルクラスを追加します。次のコードをコピーしてクラスに貼り付けます

namespace AzureCosmosEFCoreCRUD.Models
{
    public class Company
    {
        public string Name { get; set; }
        public string City { get; set; }
        public string Province { get; set; }
        public string Country { get; set; }
    }
}

C#

using Newtonsoft.Json;
using System;
using System.ComponentModel.DataAnnotations;

namespace AzureCosmosEFCoreCRUD.Models
{
    public class Videogames
    {
        [Key]
        [JsonProperty(PropertyName = "id")]
        public string Id { get; set; } = Guid.NewGuid().ToString();
        public string Name { get; set; }
        public string Genere { get; set; }
        public string Platform { get; set; }
        public Company Company { get; set; }
    }
}

C#

ステップ5-スタートアップクラスを編集する

ConfigureServicesメソッドで、ApplicationDbContextを使用してCosmos DBを構成するには、次のコード行を追加する必要があります。

var accountEndpoint = Configuration.GetValue<string>("CosmosDb:Account");
var accountKey = Configuration.GetValue<string>("CosmosDb:Key");
var dbName = Configuration.GetValue<string>("CosmosDb:DatabaseName");
services.AddDbContext<ApplicationDbContext>(x => x.UseCosmos(accountEndpoint, accountKey, dbName));

C#

ステップ6-コントローラーを追加する

Controllersフォルダーに、VideogameControllerという新しいControllerクラスを追加します。次のコードをコピーしてクラスに貼り付けます。

これらは、LINQスタイルのクエリを使用してDbContextを使用してデータベースでCRUD操作を簡単に実行する方法を示す単純なエンドポイントです。 

using AzureCosmosEFCoreCRUD.DBContext;
using AzureCosmosEFCoreCRUD.Models;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace AzureCosmosEFCoreCRUD.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class VideogameController : ControllerBase
    {
        private readonly ILogger _logger;
        private readonly ApplicationDbContext applicationDbContext;
        private readonly IConfiguration configuration;

        public VideogameController(ApplicationDbContext applicationDbContext, IConfiguration configuration, ILogger<VideogameController> logger)
        {
            this.applicationDbContext = applicationDbContext;
            this.configuration = configuration;
            _logger = logger;
        }
        [HttpGet("GetAllVideogames")]
        public async Task<ActionResult<IList<Videogames>>> GetAllVideogames()
        {
            try
            {
                var videogames = await applicationDbContext.Videogames.ToListAsync();
                if (videogames != null)
                {
                    return Ok(videogames);
                }
                return NotFound("No results found");
            }
            catch (Exception ex)
            {
                _logger.LogError(ex.Message);
                return StatusCode(500, "Some error occured while retrieving data");
            }
        }
        [HttpGet]
        public async Task<ActionResult<IList<Videogames>>> GetVideogamesByName(string name)
        {
            try
            {
                var videogames = await applicationDbContext.Videogames.FirstOrDefaultAsync(x => x.Name == name);
                if (videogames != null)
                {
                    return Ok(videogames);
                }
                return NotFound("No results found for "+name);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex.Message);
                return StatusCode(500, "Some error occured while retrieving data");
            }
        }
        [HttpGet("GetVideogameByCompanyName")]
        public async Task<ActionResult<IList<Videogames>>> GetVideogameByCompanyName(string name)
        {
            try
            {
                var videogames = await applicationDbContext.Videogames.Where(x => x.Company.Name == name).ToListAsync();
                if (videogames != null)
                {
                    return Ok(videogames);
                }
                return NotFound("No results found for " + name);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex.Message);
                return StatusCode(500, "Some error occured while retrieving data");
            }
        }
        [HttpPost]
        public async Task<ActionResult> AddVideogame(Videogames videogame)
        {
            try
            {
                await applicationDbContext.Videogames.AddAsync(videogame);
                await applicationDbContext.SaveChangesAsync();
                return Ok();
            }
            catch(Exception ex)
            {
                _logger.LogError(ex.Message);
                return StatusCode(500, "Some error occured while adding data");
            }
        }
        [HttpDelete]
        public async Task<ActionResult> DeleteVideogameByName(string name)
        {
            try
            {
                var videogame = await applicationDbContext.Videogames.FirstOrDefaultAsync(x => x.Name == name);
                if (videogame != null)
                {
                    applicationDbContext.Remove(videogame);
                    await applicationDbContext.SaveChangesAsync();
                    return Ok();
                }
                return NotFound();
            }
            catch (Exception ex)
            {
                _logger.LogError(ex.Message);
                return StatusCode(500, "Some error occured while deleting data");
            }
        }
        [HttpPut]
        public async Task<ActionResult> UpdateVideogameByName(Videogames data)
        {
            try
            {
                var videogame = await applicationDbContext.Videogames.FirstOrDefaultAsync(x => x.Name == data.Name);
                if (videogame != null)
                {
                    var itemBody = applicationDbContext.Videogames.WithPartitionKey(videogame.Id);
                    itemBody.FirstOrDefault().Platform = "XBOX";
                    applicationDbContext.Update(itemBody.FirstOrDefault());
                    await applicationDbContext.SaveChangesAsync();
                    return Ok();
                }
                return NotFound();
            }
            catch (Exception ex)
            {
                _logger.LogError(ex.Message);
                return StatusCode(500, "Some error occured while updating data");
            }
        }
    }
}

C#

概要

これは、EFCoreを使用して.NET5 RESTAPIを使用してAzureCosmosDBでCRUD操作を実行する方法のベースとして機能する非常に基本的な記事です。

 リンク:https ://www.c-sharpcorner.com/article/create-a-net-5-app-to-perform-crud-operations-on-azure-cosmos-db-sql-api-usin/

#dotnet  #crud  #aruze 

What is GEEK

Buddha Community

Azure CosmosDBでCRUD操作を実行する
Eric  Bukenya

Eric Bukenya

1624713540

Learn NoSQL in Azure: Diving Deeper into Azure Cosmos DB

This article is a part of the series – Learn NoSQL in Azure where we explore Azure Cosmos DB as a part of the non-relational database system used widely for a variety of applications. Azure Cosmos DB is a part of Microsoft’s serverless databases on Azure which is highly scalable and distributed across all locations that run on Azure. It is offered as a platform as a service (PAAS) from Azure and you can develop databases that have a very high throughput and very low latency. Using Azure Cosmos DB, customers can replicate their data across multiple locations across the globe and also across multiple locations within the same region. This makes Cosmos DB a highly available database service with almost 99.999% availability for reads and writes for multi-region modes and almost 99.99% availability for single-region modes.

In this article, we will focus more on how Azure Cosmos DB works behind the scenes and how can you get started with it using the Azure Portal. We will also explore how Cosmos DB is priced and understand the pricing model in detail.

How Azure Cosmos DB works

As already mentioned, Azure Cosmos DB is a multi-modal NoSQL database service that is geographically distributed across multiple Azure locations. This helps customers to deploy the databases across multiple locations around the globe. This is beneficial as it helps to reduce the read latency when the users use the application.

As you can see in the figure above, Azure Cosmos DB is distributed across the globe. Let’s suppose you have a web application that is hosted in India. In that case, the NoSQL database in India will be considered as the master database for writes and all the other databases can be considered as a read replicas. Whenever new data is generated, it is written to the database in India first and then it is synchronized with the other databases.

Consistency Levels

While maintaining data over multiple regions, the most common challenge is the latency as when the data is made available to the other databases. For example, when data is written to the database in India, users from India will be able to see that data sooner than users from the US. This is due to the latency in synchronization between the two regions. In order to overcome this, there are a few modes that customers can choose from and define how often or how soon they want their data to be made available in the other regions. Azure Cosmos DB offers five levels of consistency which are as follows:

  • Strong
  • Bounded staleness
  • Session
  • Consistent prefix
  • Eventual

In most common NoSQL databases, there are only two levels – Strong and EventualStrong being the most consistent level while Eventual is the least. However, as we move from Strong to Eventual, consistency decreases but availability and throughput increase. This is a trade-off that customers need to decide based on the criticality of their applications. If you want to read in more detail about the consistency levels, the official guide from Microsoft is the easiest to understand. You can refer to it here.

Azure Cosmos DB Pricing Model

Now that we have some idea about working with the NoSQL database – Azure Cosmos DB on Azure, let us try to understand how the database is priced. In order to work with any cloud-based services, it is essential that you have a sound knowledge of how the services are charged, otherwise, you might end up paying something much higher than your expectations.

If you browse to the pricing page of Azure Cosmos DB, you can see that there are two modes in which the database services are billed.

  • Database Operations – Whenever you execute or run queries against your NoSQL database, there are some resources being used. Azure terms these usages in terms of Request Units or RU. The amount of RU consumed per second is aggregated and billed
  • Consumed Storage – As you start storing data in your database, it will take up some space in order to store that data. This storage is billed per the standard SSD-based storage across any Azure locations globally

Let’s learn about this in more detail.

#azure #azure cosmos db #nosql #azure #nosql in azure #azure cosmos db

Ruthie  Bugala

Ruthie Bugala

1620435660

How to set up Azure Data Sync between Azure SQL databases and on-premises SQL Server

In this article, you learn how to set up Azure Data Sync services. In addition, you will also learn how to create and set up a data sync group between Azure SQL database and on-premises SQL Server.

In this article, you will see:

  • Overview of Azure SQL Data Sync feature
  • Discuss key components
  • Comparison between Azure SQL Data sync with the other Azure Data option
  • Setup Azure SQL Data Sync
  • More…

Azure Data Sync

Azure Data Sync —a synchronization service set up on an Azure SQL Database. This service synchronizes the data across multiple SQL databases. You can set up bi-directional data synchronization where data ingest and egest process happens between the SQL databases—It can be between Azure SQL database and on-premises and/or within the cloud Azure SQL database. At this moment, the only limitation is that it will not support Azure SQL Managed Instance.

#azure #sql azure #azure sql #azure data sync #azure sql #sql server

Ron  Cartwright

Ron Cartwright

1600624800

Getting Started With Azure Event Grid Viewer

In the last article, we had a look at how to start with Azure DevOps: Getting Started With Audit Streaming With Event Grid

In the article, we will go to the next step to create a subscription and use webhook event handlers to view those logs in our Azure web application.

#cloud #tutorial #azure #event driven architecture #realtime #signalr #webhook #azure web services #azure event grid #azure #azure event grid #serverless architecture #application integration

Aisu  Joesph

Aisu Joesph

1626490533

Azure Series #2: Single Server Deployment (Output)

No organization that is on the growth path or intending to have a more customer base and new entry into the market will restrict its infrastructure and design for one Database option. There are two levels of Database selection

  • a.  **The needs assessment **
  • **b. Selecting the kind of database **
  • c. Selection of Queues for communication
  • d. Selecting the technology player

Options to choose from:

  1. Transactional Databases:
    • Azure selection — Data Factory, Redis, CosmosDB, Azure SQL, Postgres SQL, MySQL, MariaDB, SQL Database, Maria DB, Managed Server
  2. Data warehousing:
    • Azure selection — CosmosDB
    • Delta Lake — Data Brick’s Lakehouse Architecture.
  3. Non-Relational Database:
  4. _- _Azure selection — CosmosDB
  5. Data Lake:
    • Azure Data Lake
    • Delta Lake — Data Bricks.
  6. Big Data and Analytics:
    • Data Bricks
    • Azure — HDInsights, Azure Synapse Analytics, Event Hubs, Data Lake Storage gen1, Azure Data Explorer Clusters, Data Factories, Azure Data Bricks, Analytics Services, Stream Analytics, Website UI, Cognitive Search, PowerBI, Queries, Reports.
  7. Machine Learning:
    • Azure — Azure Synapse Analytics, Machine Learning, Genomics accounts, Bot Services, Machine Learning Studio, Cognitive Services, Bonsai.

Key Data platform services would like to highlight

  • 1. Azure Data Factory (ADF)
  • 2. Azure Synapse Analytics
  • 3. Azure Stream Analytics
  • 4. Azure Databricks
  • 5. Azure Cognitive Services
  • 6. Azure Data Lake Storage
  • 7. Azure HDInsight
  • 8. Azure CosmosDB
  • 9. Azure SQL Database

#azure-databricks #azure #microsoft-azure-analytics #azure-data-factory #azure series

Ruthie  Bugala

Ruthie Bugala

1620431700

Analyze Azure Cosmos DB data using Azure Synapse Analytics

This article will help you understand how to analyze Azure Cosmos DB data using Azure Synapse Analytics.

Introduction

Azure Cosmos DB is a multi-model NoSQL database that supports hosting various types of data that are transactional in nature. OLTP systems employ transactional databases for hosting operational data. To analyze large volumes of transactional data, relational databases do not scale or perform to the needs of large-scale analytics. Columnar data warehouses are one of the preferred, effective, and proven means of analyzing and aggregating large volumes of data for big data scale analytics. Azure Synapse is the data warehouse offering in the Microsoft Azure technology stack. The challenge with analyzing transactional data in relational databases using columnar warehouses is that one needs to replicate and/or relocate data from operational repositories into analytical repositories. Hybrid transactional analytical processing (HTAP) is a methodology or approach where data hosted in a relational format is auto-organized in a columnar format eliminating the need to replicate and/or relocate the data to a great extent. Azure offers a feature to analyze data hosted in Cosmos DB using Azure Synapse. In this article, we will learn how to implement the same.

Pre-requisites

We are assuming that we are hosting data in the Cosmos DB instance. To simulate this assumption, we would need an Azure Cosmos DB account implemented using the Core (SQL) API, with all the preview features turned on. Once you have an account created, you would be able to see an account listed as shown below.

#azure #sql azure #azure synapse analytics #azure