1. 程式人生 > >Azure Cosmos DB (二) SQL API 操作

Azure Cosmos DB (二) SQL API 操作

一,引言

  還記得國慶期間,我們學習了一下關於Azure Cosmos DB 的一些基礎知識以及Azure Cosmos DB 的幾種支援資料庫型別。今天就開始分享一些實戰操作,如何通過Azure Portal 建立 Cosmos DB,以及在實際專案中如何通過程式碼操作資料庫。

  今天要演示的是 Core(SQL) 核心,SQL API 是具有豐富的SQL查詢功能的無架構 JSON 資料庫引擎,它是以 json 形式的文件資料庫。同時微軟提供了對應的 EF 的操作包 ----- Microsoft.EntityFrameworkCore.Cosmos,使得我們很輕鬆的使用原有EF操作資料庫的模式進行操作 Cosmos DB。

注意這裡使用的  Microsoft.EntityFrameworkCore.Cosmos 僅適用於 Azure Cosmos DB 的 SQL API

--------------------我是分割線--------------------

1,Azure Cosmos DB (一) 入門介紹

2,Azure Cosmos DB (二) SQL API 操作

二,正文

1, 建立Azure Cosmos DB 

在Azure portal 中點選 “+ 建立資源”,在搜尋框中輸入 “Azure Cosmos DB” 進行搜尋

點選 “Create” ,進行開始建立

Resource Group:"Web_Test_DB_RG"

Account Name:"cnbateblogwebcosmosdb"

API 選擇:Core(SQL)

Capacity mode 選擇預設 :“Provisioned throughtput”(預配的吞吐量)

其他都選擇預設。點選 “Review + create” 進行建立前的預校驗。

使用Azure Cosmos DB 免費層時,將在賬戶中免費獲得 400 RU/秒和 5GB 的儲存。每個訂閱最多可對一個賬戶啟用免費層。預計每個賬戶每月有24美元的折扣。

可以看到驗證提示 “Validation Sucess”,點選 ”Create“ 進行建立

等待幾分鐘後,我們可以在 "Web_Test_DB_RG" 中找到剛剛建立好的叫 ”cnbateblogwebcosmosdb“ 的 Cosmos DB 了

點選進去,找到 Data Explorer ,點選 ”New Database“ 新建資料庫

或者點選 ”New Container“ 旁邊的小箭頭,進行下拉選擇建立新的資料庫。

Database id:”CNBATEBLOGWEB“

點選 “OK” ,進行建立

可以看到 “CNBATEBLOGWEB” 的 Database 已建立好了。

2,專案新增對Cosmos DB 的依賴包

2.1,安裝 “Microsoft.EntityFrameworkCore”,“Microsoft.EntityFrameworkCore.Cosmos”

使用程式包管理控制檯進行安裝

Install-Package Microsoft.EntityFrameworkCore -Version 3.1.8
Install-Package Microsoft.EntityFrameworkCore.Cosmos -Version 3.1.8

2.2,要建立所需的容器並插入種子資料

配置環境,此時需要cosmosDB 的 Endpoint,Key,DatabaseName

圖中對應的 URL=》Endpoint,PRIMARK KEY=》Key,

上面步驟中建立的叫 “CNBATEBLOGWEB” 的我們需要的DatabaseName

整理好剛才需要的三個引數,新增到專案的配置檔案中 也就是 appsettings.json 檔案中

建立UserModel 實體,UserContext,重寫 OnConfiguring 方法,呼叫UseCosmos 方法

重寫 “OnModelCreating” 建立資料資料對映關係

”ConfigrueServices“ 中新增對 “UserContext” 的依賴注入

生產種子資料,先將已有的資料庫進行刪除操作,再進行新增操作以及生成種子資料

 完整程式碼

 1 public class UserContext : DbContext
 2     {
 3         public UserContext(DbContextOptions<UserContext> options) : base(options)
 4         {
 5 
 6         }
 7 
 8         public DbSet<UserModel> Users { get; set; }
 9 
10         /// <summary>
11         /// 重寫連線資料庫
12         /// </summary>
13         /// <param name="optionsBuilder"></param>
14         protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
15         {
16             // 從 appsetting.json 中獲取配置資訊
17             var config = new ConfigurationBuilder()
18                 .SetBasePath(Directory.GetCurrentDirectory())
19                 .AddJsonFile("appsettings.json")
20                 .Build();
21 
22             // 定義要使用的資料庫
23             optionsBuilder.UseCosmos(Appsettings.app("CosmosDB", "Endpoint"), Appsettings.app("CosmosDB", "Key"), Appsettings.app("CosmosDB", "DataBase"));
24         }
25 
26         protected override void OnModelCreating(ModelBuilder modelBuilder)
27         {
28             //針對於HasData限制(即使主鍵是由資料庫生成的自動增長),也需要指定主鍵 
29 
30             //呼叫EnsureCreated方法只針對與新增資料有效,但是資料庫如果有資料的話,
31             //也就是對資料更改將無效
32             Console.WriteLine("**********UserModel表開始初始化資料**********");
33             #region 資料庫資料對映
34             modelBuilder.Entity<UserModel>().HasData(
35                    //new Blog{Id=1,Name="DDD領域驅動模型"},
36                    new UserModel { Id = 1, Name = "EntityFramework Core 3.1.1" },
37                   new UserModel { Id = 2, Name = "EntityFramework Core 3.1.6" });
38 
39             #endregion
40 
41 
42         }
43 
44     }
UserContext.cs
 1 public class UserModel
 2     {
 3         public int Id { get; set; }
 4 
 5         public string Name { get; set; }
 6 
 7         public int Age { get; set; }
 8 
 9         public string Address { get; set; }
10 
11         public string Remark { get; set; }
12     }
UserModel.cs
 1    /// <summary>
 2     /// appsettings.json操作類
 3     /// </summary>
 4     public class Appsettings
 5     {
 6         static IConfiguration Configuration { get; set; }
 7         static string contentPath { get; set; }
 8 
 9         public Appsettings(string contentPath)
10         {
11             string Path = "appsettings.json";
12 
13 
14             //如果你把配置檔案 是 根據環境變數來分開了,可以這樣寫
15             //string Path = $"appsettings.{Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT")}.json";
16 
17             //var contentPath = env.ContentRootPath;
18             Configuration = new ConfigurationBuilder()
19                .SetBasePath(contentPath)
20                .Add(new JsonConfigurationSource { Path = Path, Optional = false, ReloadOnChange = true })//這樣的話,可以直接讀目錄裡的json檔案,而不是 bin 資料夾下的,所以不用修改複製屬性
21                .Build();
22         }
23 
24         /// <summary>
25         /// 封裝要操作的字元
26         /// </summary>
27         /// <param name="sections"></param>
28         /// <returns></returns>
29         public static string app(params string[] sections)
30         {
31             try
32             {
33                 var val = string.Empty;
34                 for (int i = 0; i < sections.Length; i++)
35                 {
36                     val += sections[i] + ":";
37                 }
38 
39                 return Configuration[val.TrimEnd(':')];
40             }
41             catch (Exception)
42             {
43                 return "";
44             }
45         }
46     }
Appsettings.json
 1     public class Program
 2     {
 3         public static void Main(string[] args)
 4         {
 5             var host = CreateHostBuilder(args).Build();
 6             // 建立可用於解析作用域服務的新 Microsoft.Extensions.DependencyInjection.IServiceScope。
 7             using (var scope = host.Services.CreateScope())
 8             {
 9                 var services = scope.ServiceProvider;
10                 var loggerFactory = services.GetRequiredService<ILoggerFactory>();
11                 var env = services.GetRequiredService<IWebHostEnvironment>();
12                 if (env.IsDevelopment())
13                 {
14                     try
15                     {
16                         // 從 system.IServicec提供程式獲取 T 型別的服務。
17                         var context = services.GetRequiredService<UserContext>();
18                         
19                         context.Database.EnsureDeleted();
20                         Console.WriteLine("**********開始初始化資料**********");
21                         context.Database.EnsureCreated();
22 
23                     }
24                     catch (Exception e)
25                     {
26                         var logger = loggerFactory.CreateLogger<Program>();
27                         logger.LogError(e, "Error occured seeding the Database.");
28                     }
29                 }
30             }
31 
32             // 執行 web 應用程式並阻止呼叫執行緒, 直到主機關閉。
33             // 建立完 WebHost 之後,便呼叫它的 Run 方法,而 Run 方法會去呼叫 WebHost 的 StartAsync 方法
34             // 將Initialize方法建立的Application管道傳入以供處理訊息
35             // 執行HostedServiceExecutor.StartAsync方法
36 
37             host.Run();
38         }
39 
40         public static IHostBuilder CreateHostBuilder(string[] args) =>
41             Host.CreateDefaultBuilder(args)
42                 .ConfigureWebHostDefaults(webBuilder =>
43                 {
44                     webBuilder
45                     .UseUrls("http://*:9001")
46                     .UseStartup<Startup>();
47                 });
48     }
Program.cs
 1 public class Startup
 2     {
 3         public Startup(IConfiguration configuration, IWebHostEnvironment env)
 4         {
 5             Env = env;
 6             Configuration = configuration;
 7         }
 8 
 9         public IConfiguration Configuration { get; }
10 
11         public IWebHostEnvironment Env { get; }
12 
13         // This method gets called by the runtime. Use this method to add services to the container.
14         public void ConfigureServices(IServiceCollection services)
15         {
16             services.AddSingleton(new Appsettings(Env.ContentRootPath));
17 
18             services.AddDbContext<UserContext>(options => options.UseCosmos(Appsettings.app("CosmosDB", "Endpoint"), Appsettings.app("CosmosDB", "Key"), Appsettings.app("CosmosDB", "DataBase")));
19 
20             services.AddControllersWithViews();
21         }
22 
23         // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
24         public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
25         {
26             if (env.IsDevelopment())
27             {
28                 app.UseDeveloperExceptionPage();
29             }
30             else
31             {
32                 app.UseExceptionHandler("/Home/Error");
33             }
34             app.UseStaticFiles();
35 
36             app.UseRouting();
37 
38             app.UseAuthorization();
39 
40             app.UseEndpoints(endpoints =>
41             {
42                 endpoints.MapControllerRoute(
43                     name: "default",
44                     pattern: "{controller=Home}/{action=Index}/{id?}");
45             });
46         }
47     }
Startup.cs

 3,執行專案,檢視測試結果

我們可以看到UserModel 表已初始化資料完成

 我們轉到Azure Portal 上檢視 "CNBATEBLOGWEB" 資料庫下多了叫 “UserContext” 的 Container 這裡的可以理解成存放表的容器

同時,我們可以看到 ”UserContext“ 下的 Item 多了兩條 Usermodel 資料,我們分別進行檢視,可以看到這兩條資料就是剛剛生成的種子資料

ok,今天的分享就到此,撒花是