Razor Pages 上教學課程系列的第 4 部分

注意

這不是這篇文章的最新版本。 如需目前版本,請參閱本文的 .NET 8 版本

重要

這些發行前產品的相關資訊在產品正式發行前可能會有大幅修改。 Microsoft 對此處提供的資訊,不做任何明確或隱含的瑕疵擔保。

如需目前版本,請參閱本文的 .NET 8 版本

作者:Joe Audette

RazorPagesMovieContext 物件會處理連線到資料庫和將 Movie 物件對應至資料庫記錄的工作。 資料庫內容會在 Program.cs 中向相依性插入容器註冊:

using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using RazorPagesMovie.Data;
var builder = WebApplication.CreateBuilder(args);

// Add services to the container.
builder.Services.AddRazorPages();
builder.Services.AddDbContext<RazorPagesMovieContext>(options =>
    options.UseSqlServer(builder.Configuration.GetConnectionString("RazorPagesMovieContext") ?? throw new InvalidOperationException("Connection string 'RazorPagesMovieContext' not found.")));

var app = builder.Build();

ASP.NET Core 組態系統會讀取 ConnectionString 索引鍵。 對於本機開發,組態會從 appsettings.json 檔案取得連接字串。

產生的連接字串類似於下列 JSON:

{
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft": "Warning",
      "Microsoft.Hosting.Lifetime": "Information"
    }
  },
  "AllowedHosts": "*",
  "ConnectionStrings": {
    "RazorPagesMovieContext": "Server=(localdb)\\mssqllocaldb;Database=RazorPagesMovieContext-bc;Trusted_Connection=True;MultipleActiveResultSets=true"
  }
}

將應用程式部署到測試或生產環境伺服器時,可以使用環境變數來設定測試和生產資料庫伺服器的連接字串。 如需詳細資訊,請參閱組態

SQL Server Express LocalDB

LocalDB 為輕量版的 SQL Server Express 資料庫引擎,鎖定程式開發為其目標。 LocalDB 會依需求啟動,並以使用者模式執行,因此沒有複雜的組態。 LocalDB 資料庫預設會在 C:\Users\<user>\ 目錄中建立 *.mdf 檔案。

  1. 從 [檢視] 功能表中,開啟 [SQL Server 物件總管] (SSOX)。

    檢視功能表

  2. 以滑鼠右鍵按一下 Movie 資料表,並選取 [檢視表設計工具]

    在 Movie 資料表上開啟的操作功能表

    在設計工具中開啟的 Movie 資料表

    請注意 ID 旁的索引鍵圖示。 根據預設,EF 會為主索引鍵建立名為 ID 的屬性。

  3. 以滑鼠右鍵按一下 Movie 資料表,並選取 [檢視資料]

    開啟的電影資料表,其中顯示資料表資料

植入資料庫

使用下列程式碼,在 Models 資料夾中建立名為 SeedData 的新類別:

using Microsoft.EntityFrameworkCore;
using RazorPagesMovie.Data;

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.Data;
using RazorPagesMovie.Models;

var builder = WebApplication.CreateBuilder(args);

builder.Services.AddRazorPages();
builder.Services.AddDbContext<RazorPagesMovieContext>(options =>
    options.UseSqlServer(builder.Configuration.GetConnectionString("RazorPagesMovieContext") ?? throw new InvalidOperationException("Connection string 'RazorPagesMovieContext' not found.")));

var app = builder.Build();

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

    SeedData.Initialize(services);
}

if (!app.Environment.IsDevelopment())
{
    app.UseExceptionHandler("/Error");
    app.UseHsts();
}

app.UseHttpsRedirection();
app.UseStaticFiles();

app.UseRouting();

app.UseAuthorization();

app.MapRazorPages();

app.Run();

在先前的程式碼中,已將 Program.cs 修改為執行下列動作:

  • 從相依性插入 (DI) 容器中取得資料庫內容執行個體。
  • 呼叫 seedData.Initialize 方法,並傳遞至資料庫內容執行個體。
  • 種子方法完成時處理內容。 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()) 上並逐步執行程式碼。

應用程式會顯示植入的資料:

在瀏覽器中開啟的電影應用程式顯示電影資料

下一步

RazorPagesMovieContext 物件會處理連線到資料庫和將 Movie 物件對應至資料庫記錄的工作。 資料庫內容會在 Program.cs 中向相依性插入容器註冊:

using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using RazorPagesMovie.Data;
var builder = WebApplication.CreateBuilder(args);

// Add services to the container.
builder.Services.AddRazorPages();
builder.Services.AddDbContext<RazorPagesMovieContext>(options =>
    options.UseSqlServer(builder.Configuration.GetConnectionString("RazorPagesMovieContext") ?? throw new InvalidOperationException("Connection string 'RazorPagesMovieContext' not found.")));

var app = builder.Build();

ASP.NET Core 組態系統會讀取 ConnectionString 索引鍵。 對於本機開發,組態會從 appsettings.json 檔案取得連接字串。

產生的連接字串類似於下列 JSON:

{
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft": "Warning",
      "Microsoft.Hosting.Lifetime": "Information"
    }
  },
  "AllowedHosts": "*",
  "ConnectionStrings": {
    "RazorPagesMovieContext": "Server=(localdb)\\mssqllocaldb;Database=RazorPagesMovieContext-bc;Trusted_Connection=True;MultipleActiveResultSets=true"
  }
}

將應用程式部署到測試或生產環境伺服器時,可以使用環境變數來設定測試和生產資料庫伺服器的連接字串。 如需詳細資訊,請參閱組態

SQL Server Express LocalDB

LocalDB 為輕量版的 SQL Server Express 資料庫引擎,鎖定程式開發為其目標。 LocalDB 會依需求啟動,並以使用者模式執行,因此沒有複雜的組態。 LocalDB 資料庫預設會在 C:\Users\<user>\ 目錄中建立 *.mdf 檔案。

  1. 從 [檢視] 功能表中,開啟 [SQL Server 物件總管] (SSOX)。

    檢視功能表

  2. 以滑鼠右鍵按一下 Movie 資料表,並選取 [檢視表設計工具]

    在 Movie 資料表上開啟的操作功能表

    在設計工具中開啟的 Movie 資料表

    請注意 ID 旁的索引鍵圖示。 根據預設,EF 會為主索引鍵建立名為 ID 的屬性。

  3. 以滑鼠右鍵按一下 Movie 資料表,並選取 [檢視資料]

    開啟的電影資料表,其中顯示資料表資料

植入資料庫

使用下列程式碼,在 Models 資料夾中建立名為 SeedData 的新類別:

using Microsoft.EntityFrameworkCore;
using RazorPagesMovie.Data;

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.Data;
using RazorPagesMovie.Models;

var builder = WebApplication.CreateBuilder(args);

builder.Services.AddRazorPages();
builder.Services.AddDbContext<RazorPagesMovieContext>(options =>
    options.UseSqlServer(builder.Configuration.GetConnectionString("RazorPagesMovieContext") ?? throw new InvalidOperationException("Connection string 'RazorPagesMovieContext' not found.")));

var app = builder.Build();

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

    SeedData.Initialize(services);
}

if (!app.Environment.IsDevelopment())
{
    app.UseExceptionHandler("/Error");
    app.UseHsts();
}

app.UseHttpsRedirection();
app.UseStaticFiles();

app.UseRouting();

app.UseAuthorization();

app.MapRazorPages();

app.Run();

在先前的程式碼中,已將 Program.cs 修改為執行下列動作:

  • 從相依性插入 (DI) 容器中取得資料庫內容執行個體。
  • 呼叫 seedData.Initialize 方法,並傳遞至資料庫內容執行個體。
  • 種子方法完成時處理內容。 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()) 上並逐步執行程式碼。

應用程式會顯示植入的資料:

在瀏覽器中開啟的電影應用程式顯示電影資料

下一步

RazorPagesMovieContext 物件會處理連線到資料庫和將 Movie 物件對應至資料庫記錄的工作。 資料庫內容會在 Program.cs 中向相依性插入容器註冊:

using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using RazorPagesMovie.Data;
var builder = WebApplication.CreateBuilder(args);

// Add services to the container.
builder.Services.AddRazorPages();
builder.Services.AddDbContext<RazorPagesMovieContext>(options =>
    options.UseSqlServer(builder.Configuration.GetConnectionString("RazorPagesMovieContext") ?? throw new InvalidOperationException("Connection string 'RazorPagesMovieContext' not found.")));

var app = builder.Build();

ASP.NET Core 組態系統會讀取 ConnectionString 索引鍵。 對於本機開發,組態會從 appsettings.json 檔案取得連接字串。

產生的連接字串類似於下列 JSON:

{
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft": "Warning",
      "Microsoft.Hosting.Lifetime": "Information"
    }
  },
  "AllowedHosts": "*",
  "ConnectionStrings": {
    "RazorPagesMovieContext": "Server=(localdb)\\mssqllocaldb;Database=RazorPagesMovieContext-bc;Trusted_Connection=True;MultipleActiveResultSets=true"
  }
}

將應用程式部署到測試或生產環境伺服器時,可以使用環境變數來設定測試和生產資料庫伺服器的連接字串。 如需詳細資訊,請參閱組態

SQL Server Express LocalDB

LocalDB 為輕量版的 SQL Server Express 資料庫引擎,鎖定程式開發為其目標。 LocalDB 會依需求啟動,並以使用者模式執行,因此沒有複雜的組態。 LocalDB 資料庫預設會在 C:\Users\<user>\ 目錄中建立 *.mdf 檔案。

  1. 從 [檢視] 功能表中,開啟 [SQL Server 物件總管] (SSOX)。

    檢視功能表

  2. 以滑鼠右鍵按一下 Movie 資料表,並選取 [檢視表設計工具]

    在 Movie 資料表上開啟的操作功能表

    在設計工具中開啟的 Movie 資料表

    請注意 ID 旁的索引鍵圖示。 根據預設,EF 會為主索引鍵建立名為 ID 的屬性。

  3. 以滑鼠右鍵按一下 Movie 資料表,並選取 [檢視資料]

    開啟的電影資料表,其中顯示資料表資料

植入資料庫

使用下列程式碼,在 Models 資料夾中建立名為 SeedData 的新類別:

using Microsoft.EntityFrameworkCore;
using RazorPagesMovie.Data;

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.Data;
using RazorPagesMovie.Models;
var builder = WebApplication.CreateBuilder(args);

builder.Services.AddRazorPages();
builder.Services.AddDbContext<RazorPagesMovieContext>(options =>
    options.UseSqlServer(builder.Configuration.GetConnectionString("RazorPagesMovieContext") ?? throw new InvalidOperationException("Connection string 'RazorPagesMovieContext' not found.")));

var app = builder.Build();

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

    SeedData.Initialize(services);
}

if (!app.Environment.IsDevelopment())
{
    app.UseExceptionHandler("/Error");
    app.UseHsts();
}

app.UseHttpsRedirection();
app.UseStaticFiles();

app.UseRouting();

app.UseAuthorization();

app.MapRazorPages();

app.Run();

在先前的程式碼中,已將 Program.cs 修改為執行下列動作:

  • 從相依性插入 (DI) 容器中取得資料庫內容執行個體。
  • 呼叫 seedData.Initialize 方法,並傳遞至資料庫內容執行個體。
  • 種子方法完成時處理內容。 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()) 上並逐步執行程式碼。

應用程式會顯示植入的資料:

在瀏覽器中開啟的電影應用程式顯示電影資料

下一步

檢視或下載範例程式碼 (如何下載)。

RazorPagesMovieContext 物件會處理連線到資料庫和將 Movie 物件對應至資料庫記錄的工作。 在 Startup.csConfigureServices 方法中,以相依性插入容器登錄資料庫內容:

public void ConfigureServices(IServiceCollection services)
{
    services.AddRazorPages();

    services.AddDbContext<RazorPagesMovieContext>(options =>
      options.UseSqlServer(Configuration.GetConnectionString("RazorPagesMovieContext")));
}

ASP.NET Core 組態系統會讀取 ConnectionString 索引鍵。 對於本機開發,組態會從 appsettings.json 檔案取得連接字串。

產生的連接字串類似於下列 JSON:

{
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft": "Warning",
      "Microsoft.Hosting.Lifetime": "Information"
    }
  },
  "AllowedHosts": "*",
  "ConnectionStrings": {
    "RazorPagesMovieContext": "Server=(localdb)\\mssqllocaldb;Database=RazorPagesMovieContext-bc;Trusted_Connection=True;MultipleActiveResultSets=true"
  }
}

將應用程式部署到測試或生產環境伺服器時,可以使用環境變數來設定測試和生產資料庫伺服器的連接字串。 如需詳細資訊,請參閱組態

SQL Server Express LocalDB

LocalDB 為輕量版的 SQL Server Express 資料庫引擎,鎖定程式開發為其目標。 LocalDB 會依需求啟動,並以使用者模式執行,因此沒有複雜的組態。 LocalDB 資料庫預設會在 C:\Users\<user>\ 目錄中建立 *.mdf 檔案。

  1. 從 [檢視] 功能表中,開啟 [SQL Server 物件總管] (SSOX)。

    檢視功能表

  2. 以滑鼠右鍵按一下 Movie 資料表,並選取 [檢視表設計工具]

    在 Movie 資料表上開啟的操作功能表

    在設計工具中開啟的 Movie 資料表

    請注意 ID 旁的索引鍵圖示。 根據預設,EF 會為主索引鍵建立名為 ID 的屬性。

  3. 以滑鼠右鍵按一下 Movie 資料表,並選取 [檢視資料]

    開啟的電影資料表,其中顯示資料表資料

植入資料庫

使用下列程式碼,在 Models 資料夾中建立名為 SeedData 的新類別:

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();
            }
        }
    }
}

如果資料庫中有任何電影,則種子初始設定式會返回,而且不會新增任何電影。

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

新增種子初始設定式

使用下列程式碼取代 Program.cs 的內容:

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>();
                });
    }
}

在先前的程式碼中,已將 Main 方法修改為執行下列動作:

  • 從相依性插入容器中取得資料庫內容執行個體。
  • 呼叫 seedData.Initialize 方法,並傳遞至資料庫內容執行個體。
  • 種子方法完成時處理內容。 using 語句可確保內容獲得處置。

要是未執行 Update-Database,即會發生下列例外狀況:

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

測試應用程式

  1. 刪除資料庫中的所有記錄。 使用瀏覽器中的刪除連結,或從 SSOX

  2. 透過叫用 Startup 類別中的方法強制應用程式初始化,從而執行植入方法。 若要強制初始化,IIS Express 必須停止並重新啟動。 使用下列任何方法停止並重新啟動 IIS:

    1. 以滑鼠右鍵按一下通知區域中的 IIS Express 系統匣圖示,然後選取 [結束] 或 [停止站台]

      IIS Express 系統匣圖示

      操作功能表

    2. 如果應用程式以非偵錯模式執行,請按 F5 以偵錯模式執行。

    3. 如果應用程式處於偵錯模式,請停止偵錯工具,然後按 F5

應用程式會顯示植入的資料:

在瀏覽器中開啟的電影應用程式顯示電影資料

下一步

檢視或下載範例程式碼 (如何下載)。

RazorPagesMovieContext 物件會處理連線到資料庫和將 Movie 物件對應至資料庫記錄的工作。 在 Startup.csConfigureServices 方法中,以相依性插入容器登錄資料庫內容:

public void ConfigureServices(IServiceCollection services)
{
    services.AddRazorPages();

    services.AddDbContext<RazorPagesMovieContext>(options =>
      options.UseSqlServer(Configuration.GetConnectionString("RazorPagesMovieContext")));
}

ASP.NET Core 組態系統會讀取 ConnectionString 索引鍵。 對於本機開發,組態會從 appsettings.json 檔案取得連接字串。

產生的連接字串會類似下列內容:

{
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft": "Warning",
      "Microsoft.Hosting.Lifetime": "Information"
    }
  },
  "AllowedHosts": "*",
  "ConnectionStrings": {
    "RazorPagesMovieContext": "Server=(localdb)\\mssqllocaldb;Database=RazorPagesMovieContext-bc;Trusted_Connection=True;MultipleActiveResultSets=true"
  }
}

將應用程式部署到測試或生產環境伺服器時,可以使用環境變數來設定測試和生產資料庫伺服器的連接字串。 如需詳細資訊,請參閱組態

SQL Server Express LocalDB

LocalDB 為輕量版的 SQL Server Express 資料庫引擎,鎖定程式開發為其目標。 LocalDB 會依需求啟動,並以使用者模式執行,因此沒有複雜的組態。 LocalDB 資料庫預設會在 C:\Users\<user>\ 目錄中建立 *.mdf 檔案。

  • 從 [檢視] 功能表中,開啟 [SQL Server 物件總管] (SSOX)。

    檢視功能表

  • 以滑鼠右鍵按一下 Movie 資料表,並選取 [檢視表設計工具]

    在 Movie 資料表上開啟的操作功能表

    在設計工具中開啟的 Movie 資料表

請注意 ID 旁的索引鍵圖示。 根據預設,EF 會為主索引鍵建立名為 ID 的屬性。

  • 以滑鼠右鍵按一下 Movie 資料表,並選取 [檢視資料]

    開啟的電影資料表,其中顯示資料表資料

植入資料庫

使用下列程式碼,在 Models 資料夾中建立名為 SeedData 的新類別:

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();
            }
        }
    }
}

如果資料庫中有任何電影,則種子初始設定式會返回,而且不會新增任何電影。

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

新增種子初始設定式

使用下列程式碼取代 Program.cs 的內容:

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>();
                });
    }
}

在先前的程式碼中,已將 Main 方法修改為執行下列動作:

  • 從相依性插入容器中取得資料庫內容執行個體。
  • 呼叫 seedData.Initialize 方法,並傳遞至資料庫內容執行個體。
  • 種子方法完成時處理內容。 using 語句可確保內容獲得處置。

要是未執行 Update-Database,即會發生下列例外狀況:

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

測試應用程式

  • 刪除資料庫中的所有記錄。 使用瀏覽器中的刪除連結,或從 SSOX

  • 透過叫用 Startup 類別中的方法強制應用程式初始化,從而執行植入方法。 若要強制初始化,IIS Express 必須停止並重新啟動。 使用下列任何方法停止並重新啟動 IIS:

    • 以滑鼠右鍵按一下通知區域中的 IIS Express 系統匣圖示,然後點選 [結束] 或 [停止站台]

      IIS Express 系統匣圖示

      操作功能表

      • 如果應用程式以非偵錯模式執行,請按 F5 以偵錯模式執行。
      • 如果應用程式處於偵錯模式,請停止偵錯工具,然後按 F5

應用程式會顯示植入的資料:

在 Chrome 中開啟的電影應用程式顯示電影資料

下一步