本节介绍数据库上下文
1, 打开 / Data/RazorPagesMovieContent.cs ,Startup.cs 文件:
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Threading.Tasks;
- using Microsoft.EntityFrameworkCore;
- using RazorPagesMovie.Models;
- namespace RazorPagesMovie.Data
- {
- public class RazorPagesMovieContext : DbContext
- {
- public RazorPagesMovieContext (DbContextOptions<RazorPagesMovieContext> options)
- : base(options)
- {
- }
- public DbSet<RazorPagesMovie.Models.Movie> Movie { get; set; }
- }
- }
RazorPagesMovieContent 对象负责连接到数据库, 并将 Movie 对象映射到数据库中的记录. 在 Start.cs 文件中, ConfigureServices 方法中向依赖关系注入 (Dependency Injection) 容器中注册数据库上下文, 第 30 行:
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Threading.Tasks;
- using Microsoft.AspNetCore.Builder;
- using Microsoft.AspNetCore.Hosting;
- using Microsoft.AspNetCore.HttpsPolicy;
- using Microsoft.Extensions.Configuration;
- using Microsoft.Extensions.DependencyInjection;
- using Microsoft.Extensions.Hosting;
- using Microsoft.EntityFrameworkCore;
- using RazorPagesMovie.Data;
- namespace RazorPagesMovie
- {
- public class Startup
- {
- public Startup(IConfiguration configuration)
- {
- Configuration = configuration;
- }
- public IConfiguration Configuration { get; }
- // This method gets called by the runtime. Use this method to add services to the container.
- public void ConfigureServices(IServiceCollection services)
- {
- services.AddRazorPages();
- services.AddDbContext<RazorPagesMovieContext>(options =>
- options.UseSqlServer(Configuration.GetConnectionString("RazorPagesMovieContext")));
- }
- // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
- public void Configure(IApplicationBuilder App, IwebHostEnvironment env)
- {
- if (env.IsDevelopment())
- {
- App.UseDeveloperExceptionPage();
- }
- else
- {
- App.UseExceptionHandler("/Error");
- // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
- App.UseHsts();
- }
- App.UseHttpsRedirection();
- App.UseStaticFiles();
- App.UseRouting();
- App.UseAuthorization();
- App.UseEndpoints(endpoints =>
- {
- endpoints.MapRazorPages();
- });
- }
- }
- }
ASP.NET Core 配置系统会从 appsettings.JSON 文件中读取数据库连接字符串 ConnectionString:
- {
- "Logging": {
- "LogLevel": {
- "Default": "Information",
- "Microsoft": "Warning",
- "Microsoft.Hosting.Lifetime": "Information"
- }
- },
- "AllowedHosts": "*",
- "ConnectionStrings": {
- "RazorPagesMovieContext": "Server=(localdb)\\mssqllocaldb;Database=RazorPagesMovieContext-6047c874-bb75-49ef-b998-62db7c5cbaf4;Trusted_Connection=True;MultipleActiveResultSets=true"
- }
- }
其中, 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)
- using Microsoft.EntityFrameworkCore;
- using Microsoft.Extensions.DependencyInjection;
- using RazorPagesMovie.Data;
- using System;
- using System.Linq;
- namespace RazorPagesMovie.Models
- {
- public static class SeedData
- {
- public static void Initialize(IServiceProvider serviceProvider)
- {
- using (var context = new RazorPagesMovieContext(
- serviceProvider.GetRequiredService< DbContextOptions<RazorPagesMovieContext>>()))
- {
- // Look for any movies.
- if (context.Movie.Any())
- {
- return; // DB has been seeded
- }
- context.Movie.AddRange(
- new Movie
- {
- Title = "When Harry Met Sally",
- ReleaseDate = DateTime.Parse("1989-2-12"),
- Genre = "Romantic Comedy",
- Price = 7.99M
- },
- new Movie
- {
- Title = "Ghostbusters",
- ReleaseDate = DateTime.Parse("1984-3-13"),
- Genre = "Comedy",
- Price = 8.99M
- },
- new Movie
- {
- Title = "Ghostbusters 2",
- ReleaseDate = DateTime.Parse("1986-2-23"),
- Genre = "Comedy",
- Price = 9.99M
- },
- new Movie
- {
- Title = "Rio Bravo",
- ReleaseDate = DateTime.Parse("1959-4-15"),
- Genre = "Western",
- Price = 3.99M
- }
- );
- context.SaveChanges();
- }
- }
- }
- }
第 18-21 行: 如果 DB 中有任何电影, 则会返回种子初始值设定项, 并且不会添加任何电影.
添加种子初始值设定项:
打开 Program.cs 文件, 修改 Main 方法:
- using Microsoft.AspNetCore.Hosting;
- using Microsoft.Extensions.DependencyInjection;
- using Microsoft.Extensions.Hosting;
- using Microsoft.Extensions.Logging;
- using RazorPagesMovie.Models;
- using System;
- namespace RazorPagesMovie
- {
- public class Program
- {
- public static void Main(string[] args)
- {
- var host = CreateHostBuilder(args).Build();
- using (var scope = host.Services.CreateScope())
- {
- var services = scope.ServiceProvider;
- try
- {
- SeedData.Initialize(services);
- }
- catch (Exception ex)
- {
- var logger = services.GetRequiredService<ILogger<Program>>();
- logger.LogError(ex, "An error occurred seeding the DB.");
- }
- }
- host.Run();
- }
- public static IHostBuilder CreateHostBuilder(string[] args) =>
- Host.CreateDefaultBuilder(args)
- .ConfigureWebHostDefaults(webBuilder =>
- {
- webBuilder.UseStartup<Startup>();
- });
- }
- }
4, 测试
1, 删除数据库中我们刚才录入的数据: 既可以从数据库中直接删除, 也可以通过 delete 页面进行
2, 退出 IIS Express
3, 再次按下 ctrl+F5, 运行. 我们发现, 即使我们已经完全删除录入的记录, 页面上还是还是有记录, 这就是数据库的种子:
下一节, 我们介绍数据的展示
创建基于 ASP.NET core 3.1 的 RazorPagesMovie 项目(四)- 使用数据库
来源: http://www.bubuko.com/infodetail-3346751.html