当前位置:网站首页>Azure cosmos dB (5). Net core console application

Azure cosmos dB (5). Net core console application

2020-12-07 15:40:29 Grant_ Allen

One , introduction

   I was talking about Azure CosmosDB Core(SQL) At the core , Used EF Core The way , Refer to the “Microsoft.EntityFrameworkCore.Cosmos” Of NuGet package , And today, a simple one , Use "Microsoft.Azure.Cosmos" To operate CosmosDB, Write a simple Demo.

-------------------- I'm the divider --------------------

1,Azure Cosmos DB ( One ) Introduction

2,Azure Cosmos DB ( Two ) SQL API operation

3,Azure Cosmos DB ( 3、 ... and ) EF Core operation CURD Demo

4,Azure Cosmos DB ( Four ) Use EF Of SQL API Remote redundancy

5,Azure Cosmos DB ( 5、 ... and )  .Net Core Console

Two , Text

1, Install dependencies

Installation pair Cosmos DB Dependence  "Microsoft.Azure.Cosmos"

Install using the package management console :

Install-Package Microsoft.Azure.Cosmos -Version 3.15.0

Other packages :

Install-Package Microsoft.Extensions.Configuration -Version 3.1.0
Install-Package Microsoft.Extensions.Configuration.FileExtensions -Version 3.1.0
Install-Package Microsoft.Extensions.Configuration.Json -Version 3.1.0

2, obtain CosmosClient,Database,Container object

 #region Create CosmosClient
 this.cosmosClient = new CosmosClient(Appsettings.app("CosmosDB", "Endpoint"), Appsettings.app("CosmosDB", "Key")); 
 #endregion

 #region Create CosmosDB
 this.database = await this.cosmosClient.CreateDatabaseIfNotExistsAsync(Appsettings.app("CosmosDB", "DataBase"));
 Console.WriteLine("Created Database:{0} Success\n", Appsettings.app("CosmosDB", "DataBase"));
 #endregion

 #region Create Container 
 this.container = await this.database.CreateContainerIfNotExistsAsync(Appsettings.app("CosmosDB", "Container"), "/id"); 
#endregion

3, Aim at Cosmos Of CRUD Method

3.1, Data initialization

 1 public async Task InitItem()
 2         {
 3             //Create a UserModel object for the Andersen family
 4             var user1 = new UserModel
 5             {
 6                 Id = "1",
 7                 Name = " zhang wuji ",
 8                 Age = 12,
 9                 Address = " Baojia street, Xicheng District, Beijing 43 Number ",
10                 Remark = " Central Conservatory of music "
11             };
12 
13             var user2 = new UserModel
14             {
15                 Id = "2",
16                 Name = " linghu chong ",
17                 Age = 20,
18                 Address = " Denghu East Road, Nanhai District, Foshan City 6 Number ",
19                 Remark = " Guangfa Business School "
20             };
21 
22             #region Query User1 of ' zhang wuji '
23             var user1s = await QueryItems(user1.Name);
24             #endregion
25 
26 
27             #region Add User1 Item
28             if (user1s.Count <= 0)
29             {
30                 ItemResponse<UserModel> user1Response = await this.container.CreateItemAsync<UserModel>(user1, new PartitionKey(user1.Id));
31 
32                 Console.WriteLine("Created Item in database with id:{0} Operation consumed {1} RUs.\n", user1Response.Resource.Id, user1Response.StatusCode);
33             }
34             #endregion
35 
36 
37             #region Query User2 of ' linghu chong '
38             var user2s = await QueryItems(user2.Name);
39             #endregion
40 
41             #region Add User2 Item
42             if (user2s.Count <= 0)
43             {
44                 ItemResponse<UserModel> user2Response = await this.container.CreateItemAsync<UserModel>(user2, new PartitionKey(user2.Id));
45 
46                 Console.WriteLine("Created Item in database with id:{0} Operation consumed {1} RUs.\n", user2Response.Resource.Id, user2Response.StatusCode);
47             }
48             #endregion
49         }
InitItem

3.2, Data query

 1 public async Task<List<UserModel>> QueryItems(string name)
 2         {
 3             var sqlQueryText = "SELECT * FROM c where 1=1";
 4 
 5             if (!string.IsNullOrEmpty(name))
 6             {
 7                 sqlQueryText += " and c.Name='" + name + "'";
 8             }
 9 
10             Console.WriteLine("Running query: {0}\n", sqlQueryText);
11 
12             QueryDefinition queryDefinition = new QueryDefinition(sqlQueryText);
13 
14             var users = new List<UserModel>();
15             var queryUsers = this.container.GetItemQueryIterator<UserModel>(queryDefinition);
16 
17 
18             while (queryUsers.HasMoreResults)
19             {
20                 FeedResponse<UserModel> currentResultSet = await queryUsers.ReadNextAsync();
21                 foreach (UserModel user in currentResultSet)
22                 {
23                     Console.WriteLine("\tRead {0}\n", user.Name);
24                     users.Add(user);
25                 }
26             }
27             return users;
28         }
QuertItem

3.3 Data modification

1 public async Task ModifyItem(string name)
2         {
3             var users = await QueryItems(name);
4 
5             var modifyUser = users.FirstOrDefault();
6             modifyUser.Address = " Shiban street, Jing'an District, Shanghai 73 get ";
7            var modifyResponse= await this.container.ReplaceItemAsync<UserModel>(modifyUser, modifyUser.Id, new PartitionKey(modifyUser.Id));
8             Console.WriteLine("name equal to '"+name+"',his family address modify {0}\n", modifyResponse.StatusCode==HttpStatusCode.OK?"success":"fail");
9         }
ModifyItem

3.4 Data deletion

1 public async Task DeleteItem(string name)
2         {
3             var users= await QueryItems(name);
4 
5            var deleteResponse= await this.container.DeleteItemAsync<UserModel>(users.First().Id, new PartitionKey(users.First().Id));
6 
7             Console.WriteLine("delete'" + name + " item'{0}\n", deleteResponse.StatusCode == HttpStatusCode.NoContent ? "success" : "fail");
8         }
DeleteItem

For the complete code, please check the... At the bottom of the article github Address

4, test result

First, we put a breakpoint in the code that performs the query operation , At the same time main As can be seen in the method, we execute in turn

1) Initialization data -----> 2) View the data -----》3) Modifying data -----》4) Delete data

Run the project , We go back to Azure Portal You can see the created "cnbateblogweb-cosmosdb" Of Azure CosmosDB, Click on “Data Explorer” Just initialized data view

Compare the log information printed by the console , You can see that the database has been initialized , Containers , as well as Item term .

VS Click on “F10” Let's look at the name first “ linghu chong ” Of Item The address of

F10 after , After performing the modification operation , View the current data , See if changes have been made

VS Continue to click on “F10” Delete , You can see in the Azure Portal You can't find “ linghu chong ” This is the number , The same console log shows “ linghu chong ” This data has been deleted .

Bingo!!! success

about Azure CosmosDB The operation of adding, deleting, modifying and checking has been completed , For the above operations , You can use it .

3、 ... and , ending

   Today we finished using “Microsoft.Azure.Cosmos” To operate Azure CosmosDB , And through a Demo It's demonstrated. Right Azure Cosmos DB Process operation , Production seed data , And how to increase the data in the database , Delete , modify , Query and so on . It's also right Azure CosmosDB A review of the technical operation of . The content shared in this article also has a lot of my own understanding , Some people don't understand well , Also contains , And point out the shortcomings !!!!!**,°*:.*( ̄▽ ̄)/$:*.°** .

Reference link :https://docs.azure.cn/zh-cn/cosmos-db/

github:https://github.com/yunqian44/Azure.CosmosDB.git

author :Allen 

Copyright : For reprint, please indicate the author and source of the article clearly . If an error is found , Welcome criticism and correction .

版权声明
本文为[Grant_ Allen]所创,转载请带上原文链接,感谢
https://chowdera.com/2020/12/20201207153949755m.html