Razor 页面教程系列第 4 部分

作者:Joe Audette

RazorPagesMovieContext 对象处理连接到数据库并将 Movie 对象映射到数据库记录的任务。 在中将数据库上下文注册到Program.cs容器:

using Microsoft.EntityFrameworkCore;
var builder = WebApplication.CreateBuilder(args);
var connectionString = builder.Configuration.GetConnectionString("RazorPagesMovieContext") ?? throw new InvalidOperationException("Connection string 'RazorPagesMovieContext' not found.");

builder.Services.AddDbContext<RazorPagesMovieContext>(options => options.UseSqlServer(connectionString));

// Add services to the container.
builder.Services.AddRazorPages();

ASP.NET Core 配置系统会读取 ConnectionString 键。 对于本地开发,配置从 appsettings.json 文件获取连接字符串。

生成的连接字符串类似于以下 JSON:

{
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft.AspNetCore": "Warning"
    }
  },
  "AllowedHosts": "*",
  "ConnectionStrings": {
    "RazorPagesMovieContext": "Server=(localdb)\\mssqllocaldb;Database=RazorPagesMovieContext-f2e0482c-952d-4b1c-afe9-a1a3dfe52e55;Trusted_Connection=True;MultipleActiveResultSets=true"
  }
}

Warning

本文使用不需要对用户进行身份验证的本地数据库。 生产应用应使用可用的最安全的身份验证流程。 有关已部署测试和生产应用的身份验证的详细信息,请参阅安全身份验证流。

SQL Server Express LocalDB(本地数据库)

LocalDB 是 SQL Server Express 数据库引擎的轻型版本,专为程序开发而设计。 LocalDB 作为按需启动并在用户模式下运行的轻量级数据库没有复杂的配置。 默认情况下,LocalDB 会在*.mdf目录中创建C:\Users\<user>\数据库文件。

  1. 在视图菜单中,打开SQL Server 对象资源管理器(SSOX)。

    显示SQL Server 对象资源管理器选项的“视图”菜单。

  2. 右键单击 Movie 表,然后选择“视图设计器”:

    在 Movie 表格上打开上下文菜单。

    电影表会在设计器中打开。

    请注意 ID 旁边的钥匙图标。 默认情况下,EF 为该主键创建一个名为 ID 的属性。

  3. 右键单击 Movie 表格,然后选择“查看数据”:

    显示表数据的打开的 Movie 表。

设定数据库种子

使用以下代码在 Models 文件夹中创建一个名为 SeedData 的新类:

using Microsoft.EntityFrameworkCore;

namespace RazorPagesMovie.Models;

public static class SeedData
{
    public static void Initialize(IServiceProvider serviceProvider)
    {
        using (var context = new RazorPagesMovieContext(
            serviceProvider.GetRequiredService<
                DbContextOptions<RazorPagesMovieContext>>()))
        {
            if (context == null || context.Movie == null)
            {
                throw new ArgumentNullException("Null 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();
        }
    }
}

如果数据库中包含任何电影,则种子初始化器将直接返回,而不添加任何电影。

if (context.Movie.Any())
{
    return;
}

添加种子初始化器

使用以下突出显示的代码更新 Program.cs:

using Microsoft.EntityFrameworkCore;
using RazorPagesMovie.Models;
var builder = WebApplication.CreateBuilder(args);
var connectionString = builder.Configuration.GetConnectionString("RazorPagesMovieContext") ?? throw new InvalidOperationException("Connection string 'RazorPagesMovieContext' not found.");

builder.Services.AddDbContext<RazorPagesMovieContext>(options => options.UseSqlServer(connectionString));

// Add services to the container.
builder.Services.AddRazorPages();

var app = builder.Build();

using (var scope = app.Services.CreateScope())
{
    var services = scope.ServiceProvider;

    SeedData.Initialize(services);
}

// Configure the HTTP request pipeline.
if (!app.Environment.IsDevelopment())
{
    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.UseRouting();

app.UseAuthorization();

app.MapStaticAssets();
app.MapRazorPages()
   .WithStaticAssets();

app.Run();

在前面的代码中,你修改 Program.cs 为执行以下步骤:

  • 使用 app.Services.CreateScope() 创建服务作用域。
  • 从作用域获取服务提供商 (IServiceProvider)。
  • 调用 SeedData.Initialize 方法,传递服务提供程序。
  • 在 Seed 方法完成时释放服务作用域。 该 using 语句可确保释放该作用域。

如果未运行 Update-Database,将发生以下异常:

SqlException: Cannot open database "RazorPagesMovieContext-" requested by the login. The login failed. Login failed for user 'user name'.

测试应用程序

删除数据库中的所有记录,以便种子方法运行。 停止并启动应用以设定数据库种子。 如果数据库未填充初始数据,请在 if (context.Movie.Any()) 上放置断点并单步执行代码。

应用将显示设定为种子的数据:

电影应用程序在浏览器中打开,其中显示了电影数据。

后续步骤