作者: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>\資料庫檔案。
從 [檢視] 功能表中,開啟 [SQL Server 物件總管] (SSOX)。
以滑鼠右鍵按一下
Movie資料表,並選取 檢視設計工具:
請注意
ID旁邊的鑰匙圖示。 根據預設,EF 會為主索引鍵建立名為ID的屬性。在
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方法,傳入服務提供者。 - 種子方法完成後,處理服務範圍。
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()) 上並逐步執行程式碼。
應用程式會顯示預先填入的資料: