码迷,mamicode.com
首页 > 数据库 > 详细

创建基于ASP.NET core 3.1的RazorPagesMovie项目(四)-使用数据库

时间:2019-12-23 22:25:42      阅读:121      评论:0      收藏:0      [点我收藏+]

标签:ilog   roman   poi   public   添加   figure   EDA   ros   ogr   

本节介绍数据库上下文

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,运行。我们发现,即使我们已经完全删除录入的记录,页面上还是还是有记录,这就是数据库的种子:

  技术图片

 

 

  下一节,我们介绍数据的展示

创建基于ASP.NET core 3.1的RazorPagesMovie项目(四)-使用数据库

标签:ilog   roman   poi   public   添加   figure   EDA   ros   ogr   

原文地址:https://www.cnblogs.com/hiwuchong/p/12082339.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!