創建基於ASP.NET core 3.1的RazorPagesMovie項目(四)-使用數據庫


本節介紹數據庫上下文

1、打開/Data/RazorPagesMovieContent.cs 、Startup.cs文件:

  

 1 using System;
 2 using System.Collections.Generic;
 3 using System.Linq;
 4 using System.Threading.Tasks;
 5 using Microsoft.EntityFrameworkCore;
 6 using RazorPagesMovie.Models;
 7 
 8 namespace RazorPagesMovie.Data
 9 {
10     public class RazorPagesMovieContext : DbContext
11     {
12         public RazorPagesMovieContext (DbContextOptions<RazorPagesMovieContext> options)
13             : base(options)
14         {
15         }
16 
17         public DbSet<RazorPagesMovie.Models.Movie> Movie { get; set; }
18     }
19 }

   RazorPagesMovieContent對象負責連接到數據庫,並將Movie對象映射到數據庫中的記錄。在Start.cs文件中,ConfigureServices方法中向依賴關系注入(Dependency Injection)容器中注冊數據庫上下文,第30行:

  

 1 using System;
 2 using System.Collections.Generic;
 3 using System.Linq;
 4 using System.Threading.Tasks;
 5 using Microsoft.AspNetCore.Builder;
 6 using Microsoft.AspNetCore.Hosting;
 7 using Microsoft.AspNetCore.HttpsPolicy;
 8 using Microsoft.Extensions.Configuration;
 9 using Microsoft.Extensions.DependencyInjection;
10 using Microsoft.Extensions.Hosting;
11 using Microsoft.EntityFrameworkCore;
12 using RazorPagesMovie.Data;
13 
14 namespace RazorPagesMovie
15 {
16     public class Startup
17     {
18         public Startup(IConfiguration configuration)
19         {
20             Configuration = configuration;
21         }
22 
23         public IConfiguration Configuration { get; }
24 
25         // This method gets called by the runtime. Use this method to add services to the container.
26         public void ConfigureServices(IServiceCollection services)
27         {
28             services.AddRazorPages();
29 
30             services.AddDbContext<RazorPagesMovieContext>(options =>
31                     options.UseSqlServer(Configuration.GetConnectionString("RazorPagesMovieContext")));
32         }
33 
34         // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
35         public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
36         {
37             if (env.IsDevelopment())
38             {
39                 app.UseDeveloperExceptionPage();
40             }
41             else
42             {
43                 app.UseExceptionHandler("/Error");
44                 // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
45                 app.UseHsts();
46             }
47 
48             app.UseHttpsRedirection();
49             app.UseStaticFiles();
50 
51             app.UseRouting();
52 
53             app.UseAuthorization();
54 
55             app.UseEndpoints(endpoints =>
56             {
57                 endpoints.MapRazorPages();
58             });
59         }
60     }
61 }

 

  ASP.NET Core 配置系統會從appsettings.json文件中讀取數據庫連接字符串ConnectionString:

 1 {
 2   "Logging": {
 3     "LogLevel": {
 4       "Default": "Information",
 5       "Microsoft": "Warning",
 6       "Microsoft.Hosting.Lifetime": "Information"
 7     }
 8   },
 9   "AllowedHosts": "*",
10   "ConnectionStrings": {
11     "RazorPagesMovieContext": "Server=(localdb)\\mssqllocaldb;Database=RazorPagesMovieContext-6047c874-bb75-49ef-b998-62db7c5cbaf4;Trusted_Connection=True;MultipleActiveResultSets=true"
12   }
13 }

 

  其中,Server表示服務器,這里是localdb\\mssqllocaldb;Database表示數據庫名稱,是一個系統自動生成的,數據庫名可以是任意的。在將程序部署到測試或者生產服務器時,可以使用環境變量將連接字符串設置為實際的數據庫服務器。以后再詳細介紹。

 

2、SQL Server Express LocalDB

  localdb,是輕型版的數據庫引擎。按需啟動。默認情況下,它將在c:\用戶\你的用戶名\目錄下創建*.mdf和*_log.ldf文件。我這里生成的如下:

    

 

 

  選擇“視圖”>"SQL Server 對象資源管理器",在對象資源管理中我們可以看到剛才生成的數據庫和表:

  

 

   在dbo.Movie表上右鍵,選擇“視圖設計器”,可以查看表格結構以及對應的TSQL和表上其他的對象:

  

 

   在dbo.Movie表上右鍵,選擇“查看數據”,可以查看我們新增的電影記錄:

  

 3、設定數據庫種子(Seed the database)

 1 using Microsoft.EntityFrameworkCore;
 2 using Microsoft.Extensions.DependencyInjection;
 3 using RazorPagesMovie.Data;
 4 using System;
 5 using System.Linq;
 6 
 7 namespace RazorPagesMovie.Models
 8 {
 9     public static class SeedData
10     {
11         public static void Initialize(IServiceProvider serviceProvider)
12         {
13             using (var context = new RazorPagesMovieContext(
14                 serviceProvider.GetRequiredService<
15                     DbContextOptions<RazorPagesMovieContext>>()))
16             {
17                 // Look for any movies.
18                 if (context.Movie.Any())
19                 {
20                     return;   // DB has been seeded
21                 }
22 
23                 context.Movie.AddRange(
24                     new Movie
25                     {
26                         Title = "When Harry Met Sally",
27                         ReleaseDate = DateTime.Parse("1989-2-12"),
28                         Genre = "Romantic Comedy",
29                         Price = 7.99M
30                     },
31 
32                     new Movie
33                     {
34                         Title = "Ghostbusters ",
35                         ReleaseDate = DateTime.Parse("1984-3-13"),
36                         Genre = "Comedy",
37                         Price = 8.99M
38                     },
39 
40                     new Movie
41                     {
42                         Title = "Ghostbusters 2",
43                         ReleaseDate = DateTime.Parse("1986-2-23"),
44                         Genre = "Comedy",
45                         Price = 9.99M
46                     },
47 
48                     new Movie
49                     {
50                         Title = "Rio Bravo",
51                         ReleaseDate = DateTime.Parse("1959-4-15"),
52                         Genre = "Western",
53                         Price = 3.99M
54                     }
55                 );
56                 context.SaveChanges();
57             }
58         }
59     }
60 }

 

   第18-21行:如果DB中有任何電影,則會返回種子初始值設定項,並且不會添加任何電影。

   添加種子初始值設定項:

  打開Program.cs文件,修改Main方法:

 1 using Microsoft.AspNetCore.Hosting;
 2 using Microsoft.Extensions.DependencyInjection;
 3 using Microsoft.Extensions.Hosting;
 4 using Microsoft.Extensions.Logging;
 5 using RazorPagesMovie.Models;
 6 using System;
 7 
 8 namespace RazorPagesMovie
 9 {
10     public class Program
11     {
12         public static void Main(string[] args)
13         {
14             var host = CreateHostBuilder(args).Build();
15 
16             using (var scope = host.Services.CreateScope())
17             {
18                 var services = scope.ServiceProvider;
19 
20                 try
21                 {
22                     SeedData.Initialize(services);
23                 }
24                 catch (Exception ex)
25                 {
26                     var logger = services.GetRequiredService<ILogger<Program>>();
27                     logger.LogError(ex, "An error occurred seeding the DB.");
28                 }
29             }
30 
31             host.Run();
32 
33         }
34 
35         public static IHostBuilder CreateHostBuilder(string[] args) =>
36             Host.CreateDefaultBuilder(args)
37                 .ConfigureWebHostDefaults(webBuilder =>
38                 {
39                     webBuilder.UseStartup<Startup>();
40                 });
41     }
42 }

 

4、測試

  1、刪除數據庫中我們剛才錄入的數據:既可以從數據庫中直接刪除,也可以通過delete頁面進行

  2、退出IIS Express

  

 

 

  3、再次按下ctrl+F5,運行。我們發現,即使我們已經完全刪除錄入的記錄,頁面上還是還是有記錄,這就是數據庫的種子:

  

 

 

  下一節,我們介紹數據的展示


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM