注意
這不是這篇文章的最新版本。 關於目前版本,請參閱 本文的 .NET 10 版本。
警告
不再支援此版本的 ASP.NET Core。 如需詳細資訊,請參閱 .NET 和 .NET Core 支持原則。 如需目前的版本,請參閱 本文的 .NET 9 版本。
作者:Rick Anderson 與 Jon P Smith。
簡介
本教學系列的這一部分著重於在 ASP.NET Core MVC 應用程式中使用 SQL 資料庫。
您將了解如何:
- 註冊並設定 Entity Framework Core 資料庫上下文,用於您的 ASP.NET Core MVC 應用程式。
- 在本地開發時使用資料庫連線字串。
- 使用 SQL Server Express LocalDB 進行開發,並使用 SQL Server 物件總管檢視你的資料庫與資料。
- 先用初始樣本資料為資料庫做種子。
先決條件
這個教學使用你在前一步建立的資料庫: 第四部分,將模型加入 ASP.NET Core MVC 應用程式。
處理資料庫上下文
MvcMovieContext 物件會處理連線到資料庫和將 Movie 物件對應至資料庫記錄的工作。 資料庫內容會向 檔案中的Program.cs容器註冊:
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddDbContext<MvcMovieContext>(options =>
options.UseSqlServer(builder.Configuration.GetConnectionString("MvcMovieContext") ?? throw new InvalidOperationException("Connection string 'MvcMovieContext' not found.")));
ASP.NET Core 組態系統會讀取 ConnectionString 索引鍵。 對於本機開發,程式會從 appsettings.json 檔案中取得連接字串以供使用:
"ConnectionStrings": {
"MvcMovieContext": "Server=(localdb)\\mssqllocaldb;Database=MvcMovieContext-4ebefa10-de29-4dea-b2ad-8a8dc6bcf374;Trusted_Connection=True;MultipleActiveResultSets=true"
}
警告
本文使用本機資料庫,其不需要使用者進行驗證。 實際執行應用程式應該使用可用的最安全驗證流程。 如需已部署測試與實際執行應用程式驗證的詳細資訊,請參閱安全驗證流程。
SQL Server Express LocalDB (本地資料庫)
LocalDB:
- 這是 SQL Server Express 資料庫引擎的輕量型版本,預設會隨 Visual Studio 一起安裝。
- 使用連接字串按需啟動。
- 專為程式開發而設計。 它會以使用者模式執行,因此沒有複雜的設定。
- 根據預設,系統會在 C:/Users/{user} 目錄中建立 .mdf 檔案。
檢查資料庫
從 [檢視] 功能表中,開啟 [SQL Server 物件總管] (SSOX)。
以滑鼠右鍵按一下 Movie 資料表 (dbo.Movie) > 檢視設計師
>
請注意 ID 旁的索引鍵圖示。 根據預設,EF 會將名為 ID 的屬性設為主索引鍵。
以滑鼠右鍵按一下 Movie 資料表 > [檢視資料]
初始化資料庫
在 SeedData 資料夾中建立名為 的新類別。 使用下列程式碼取代產生的程式碼:
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using MvcMovie.Data;
using System;
using System.Linq;
namespace MvcMovie.Models;
public static class SeedData
{
public static void Initialize(IServiceProvider serviceProvider)
{
using (var context = new MvcMovieContext(
serviceProvider.GetRequiredService<
DbContextOptions<MvcMovieContext>>()))
{
// 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; // DB has been seeded.
}
新增種子初始設定式
以下列程式碼取代 Program.cs 的內容。 新的程式碼會醒目提示顯示。
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using MvcMovie.Data;
using MvcMovie.Models;
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddDbContext<MvcMovieContext>(options =>
options.UseSqlServer(builder.Configuration.GetConnectionString("MvcMovieContext") ?? throw new InvalidOperationException("Connection string 'MvcMovieContext' not found.")));
// Add services to the container.
builder.Services.AddControllersWithViews();
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("/Home/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.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{action=Index}/{id?}");
app.Run();
刪除資料庫中的所有記錄。 您可以使用瀏覽器或 SSOX 的刪除連結來執行這項操作。
測試應用程式。 強制應用程式初始化,呼叫 Program.cs 檔案中的程式碼,讓種子方法執行。 若要強制初始化,請關閉 Visual Studio 開啟的命令提示字元視窗,然後按 Ctrl+F5 重新啟動。
應用程式會顯示植入的資料。
簡介
本教學系列的這一部分著重於在 ASP.NET Core MVC 應用程式中使用 SQL 資料庫。
您將了解如何:
- 註冊並設定 Entity Framework Core 資料庫上下文,用於您的 ASP.NET Core MVC 應用程式。
- 在本地開發時使用資料庫連線字串。
- 使用 SQL Server Express LocalDB 進行開發,並使用 SQL Server 物件總管檢視你的資料庫與資料。
- 先用初始樣本資料為資料庫做種子。
先決條件
這個教學使用你在前一步建立的資料庫: 第四部分,將模型加入 ASP.NET Core MVC 應用程式。
處理資料庫上下文
MvcMovieContext 物件會處理連線到資料庫和將 Movie 物件對應至資料庫記錄的工作。 資料庫內容會向 檔案中的Program.cs容器註冊:
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddDbContext<MvcMovieContext>(options =>
options.UseSqlServer(builder.Configuration.GetConnectionString("MvcMovieContext")));
ASP.NET Core 組態系統會讀取 ConnectionString 索引鍵。 對於本機開發,程式會從 appsettings.json 檔案中取得連接字串以供使用:
"ConnectionStrings": {
"MvcMovieContext": "Data Source=MvcMovieContext-ea7a4069-f366-4742-bd1c-3f753a804ce1.db"
}
警告
本文使用本機資料庫,其不需要使用者進行驗證。 實際執行應用程式應該使用可用的最安全驗證流程。 如需已部署測試與實際執行應用程式驗證的詳細資訊,請參閱安全驗證流程。
SQL Server Express LocalDB (本地資料庫)
LocalDB:
- 這是 SQL Server Express 資料庫引擎的輕量型版本,預設會隨 Visual Studio 一起安裝。
- 使用連接字串按需啟動。
- 專為程式開發而設計。 它會以使用者模式執行,因此沒有複雜的設定。
- 根據預設,系統會在 C:/Users/{user} 目錄中建立 .mdf 檔案。
檢查資料庫
從 [檢視] 功能表中,開啟 [SQL Server 物件總管] (SSOX)。
以滑鼠右鍵按一下 Movie 資料表 (dbo.Movie) > 檢視設計師
>
請注意 ID 旁的索引鍵圖示。 根據預設,EF 會將名為 ID 的屬性設為主索引鍵。
以滑鼠右鍵按一下 Movie 資料表 > [檢視資料]
初始化資料庫
在 SeedData 資料夾中建立名為 的新類別。 使用下列程式碼取代產生的程式碼:
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using MvcMovie.Data;
using System;
using System.Linq;
namespace MvcMovie.Models;
public static class SeedData
{
public static void Initialize(IServiceProvider serviceProvider)
{
using (var context = new MvcMovieContext(
serviceProvider.GetRequiredService<
DbContextOptions<MvcMovieContext>>()))
{
// 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; // DB has been seeded.
}
新增種子初始設定式
以下列程式碼取代 Program.cs 的內容。 新的程式碼會醒目提示顯示。
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using MvcMovie.Data;
using MvcMovie.Models;
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddDbContext<MvcMovieContext>(options =>
options.UseSqlServer(builder.Configuration.GetConnectionString("MvcMovieContext")));
// Add services to the container.
builder.Services.AddControllersWithViews();
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("/Home/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.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{action=Index}/{id?}");
app.Run();
刪除資料庫中的所有記錄。 您可以使用瀏覽器或 SSOX 的刪除連結來執行這項操作。
測試應用程式。 強制應用程式初始化,呼叫 Program.cs 檔案中的程式碼,讓種子方法執行。 若要強制初始化,請關閉 Visual Studio 開啟的命令提示字元視窗,然後按 Ctrl+F5 重新啟動。
應用程式會顯示植入的資料。
簡介
本教學系列的這一部分著重於在 ASP.NET Core MVC 應用程式中使用 SQL 資料庫。
您將了解如何:
- 註冊並設定 Entity Framework Core 資料庫上下文,用於您的 ASP.NET Core MVC 應用程式。
- 在本地開發中處理資料庫連接字串。
- 使用 SQL Server Express LocalDB 進行開發,並使用 SQL Server 物件總管檢視你的資料庫與資料。
- 先用初始樣本資料為資料庫做種子。
先決條件
這個教學使用你在前一步建立的資料庫: 第四部分,將模型加入 ASP.NET Core MVC 應用程式。
處理資料庫上下文
MvcMovieContext 物件會處理連線到資料庫和將 Movie 物件對應至資料庫記錄的工作。 資料庫內容會向 檔案中的Program.cs容器註冊:
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddDbContext<MvcMovieContext>(options =>
options.UseSqlServer(builder.Configuration.GetConnectionString("MvcMovieContext")));
ASP.NET Core 組態系統會讀取 ConnectionString 索引鍵。 對於本機開發,程式會從 appsettings.json 檔案中取得連接字串以供使用:
"ConnectionStrings": {
"MvcMovieContext": "Data Source=MvcMovieContext-ea7a4069-f366-4742-bd1c-3f753a804ce1.db"
}
警告
本文使用本機資料庫,其不需要使用者進行驗證。 實際執行應用程式應該使用可用的最安全驗證流程。 如需已部署測試與實際執行應用程式驗證的詳細資訊,請參閱安全驗證流程。
SQL Server Express LocalDB (本地資料庫)
LocalDB:
- 這是 SQL Server Express 資料庫引擎的輕量型版本,預設會隨 Visual Studio 一起安裝。
- 使用連接字串按需啟動。
- 專為程式開發而設計。 它會以使用者模式執行,因此沒有複雜的設定。
- 根據預設,系統會在 C:/Users/{user} 目錄中建立 .mdf 檔案。
檢查資料庫
從 [檢視] 功能表中,開啟 [SQL Server 物件總管] (SSOX)。
以滑鼠右鍵按一下 Movie 資料表 (dbo.Movie) > 檢視設計師
>
請注意 ID 旁的索引鍵圖示。 根據預設,EF 會將名為 ID 的屬性設為主索引鍵。
以滑鼠右鍵按一下 Movie 資料表 > [檢視資料]
初始化資料庫
在 SeedData 資料夾中建立名為 的新類別。 使用下列程式碼取代產生的程式碼:
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using MvcMovie.Data;
using System;
using System.Linq;
namespace MvcMovie.Models;
public static class SeedData
{
public static void Initialize(IServiceProvider serviceProvider)
{
using (var context = new MvcMovieContext(
serviceProvider.GetRequiredService<
DbContextOptions<MvcMovieContext>>()))
{
// 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; // DB has been seeded.
}
<a name=snippet_“si”>
新增種子初始設定式
以下列程式碼取代 Program.cs 的內容。 新的程式碼會醒目提示顯示。
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using MvcMovie.Data;
using MvcMovie.Models;
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddDbContext<MvcMovieContext>(options =>
options.UseSqlServer(builder.Configuration.GetConnectionString("MvcMovieContext")));
// Add services to the container.
builder.Services.AddControllersWithViews();
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("/Home/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.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{action=Index}/{id?}");
app.Run();
刪除資料庫中的所有記錄。 您可以使用瀏覽器或 SSOX 的刪除連結來執行這項操作。
測試應用程式。 強制應用程式初始化,呼叫 Program.cs 檔案中的程式碼,讓種子方法執行。 若要強制初始化,請關閉 Visual Studio 開啟的命令提示字元視窗,然後按 Ctrl+F5 重新啟動。
應用程式會顯示植入的資料。
簡介
本教學系列的這一部分著重於在 ASP.NET Core MVC 應用程式中使用 SQL 資料庫。
您將了解如何:
- 註冊並設定 Entity Framework Core 資料庫上下文,用於您的 ASP.NET Core MVC 應用程式。
- 本地端開發時使用資料庫連接字串。
- 使用 SQL Server Express LocalDB 進行開發,並使用 SQL Server 物件總管檢視你的資料庫與資料。
- 先用初始樣本資料為資料庫做種子。
先決條件
這個教學使用你在前一步建立的資料庫: 第四部分,將模型加入 ASP.NET Core MVC 應用程式。
處理資料庫內容
MvcMovieContext 物件會處理連線到資料庫和將 Movie 物件對應至資料庫記錄的工作。 資料庫內容會向 檔案中的Program.cs容器註冊:
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddDbContext<MvcMovieContext>(options =>
options.UseSqlServer(builder.Configuration.GetConnectionString("MvcMovieContext")));
ASP.NET Core 組態系統會讀取 ConnectionString 索引鍵。 對於本機開發,程式會從 appsettings.json 檔案中取得連接字串以供使用:
"ConnectionStrings": {
"MvcMovieContext": "Server=(localdb)\\mssqllocaldb;Database=MvcMovieContext-7dc5;Trusted_Connection=True;MultipleActiveResultSets=true"
}
警告
本文使用本機資料庫,其不需要使用者進行驗證。 實際執行應用程式應該使用可用的最安全驗證流程。 如需已部署測試與實際執行應用程式驗證的詳細資訊,請參閱安全驗證流程。
SQL Server Express LocalDB (本地資料庫)
LocalDB:
- 這是 SQL Server Express 資料庫引擎的輕量型版本,預設會隨 Visual Studio 一起安裝。
- 使用連接字串按需啟動。
- 專為程式開發而設計。 它會以使用者模式執行,因此沒有複雜的設定。
- 根據預設,系統會在 C:/Users/{user} 目錄中建立 .mdf 檔案。
初始化資料庫
在 SeedData 資料夾中建立名為 的新類別。 使用下列程式碼取代產生的程式碼:
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using MvcMovie.Data;
using System;
using System.Linq;
namespace MvcMovie.Models
{
public static class SeedData
{
public static void Initialize(IServiceProvider serviceProvider)
{
using (var context = new MvcMovieContext(
serviceProvider.GetRequiredService<
DbContextOptions<MvcMovieContext>>()))
{
// 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; // DB has been seeded.
}
新增種子初始設定式
以下列程式碼取代 Program.cs 的內容。 新的程式碼會醒目提示顯示。
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using MvcMovie.Data;
using MvcMovie.Models;
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddDbContext<MvcMovieContext>(options =>
options.UseSqlServer(builder.Configuration.GetConnectionString("MvcMovieContext")));
// Add services to the container.
builder.Services.AddControllersWithViews();
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("/Home/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.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{action=Index}/{id?}");
app.Run();
刪除資料庫中的所有記錄。 您可以使用瀏覽器或 SSOX 的刪除連結來執行這項操作。
測試應用程式。 強制應用程式初始化,呼叫 Program.cs 檔案中的程式碼,讓種子方法執行。 若要強制初始化,請關閉 Visual Studio 開啟的命令提示字元視窗,然後按 Ctrl+F5 重新啟動。
應用程式會顯示植入的資料。
簡介
本教學系列的這一部分著重於在 ASP.NET Core MVC 應用程式中使用 SQL 資料庫。
您將了解如何:
- 註冊並設定 Entity Framework Core 資料庫上下文,用於您的 ASP.NET Core MVC 應用程式。
- 在本地開發時處理資料庫連線字串。
- 使用 SQL Server Express LocalDB 進行開發,並使用 SQL Server 物件總管檢視你的資料庫與資料。
- 先用初始樣本資料為資料庫做種子。
先決條件
這個教學使用你在前一步建立的資料庫: 第四部分,將模型加入 ASP.NET Core MVC 應用程式。
處理資料庫內容
MvcMovieContext 物件會處理連線到資料庫和將 Movie 物件對應至資料庫記錄的工作。 在 檔案的 ConfigureServices 方法中,以Startup.cs容器登錄資料庫內容:
public void ConfigureServices(IServiceCollection services)
{
services.AddControllersWithViews();
services.AddDbContext<MvcMovieContext>(options =>
options.UseSqlServer(Configuration.GetConnectionString("MvcMovieContext")));
}
ASP.NET Core 組態系統會讀取 ConnectionString 索引鍵。 對於本機開發,程式會從 appsettings.json 檔案中取得連接字串以供使用:
"ConnectionStrings": {
"MvcMovieContext": "Server=(localdb)\\mssqllocaldb;Database=MvcMovieContext-2;Trusted_Connection=True;MultipleActiveResultSets=true"
}
警告
本文使用本機資料庫,其不需要使用者進行驗證。 實際執行應用程式應該使用可用的最安全驗證流程。 如需已部署測試與實際執行應用程式驗證的詳細資訊,請參閱安全驗證流程。
SQL Server Express LocalDB (本地資料庫)
LocalDB:
- 這是 SQL Server Express 資料庫引擎的輕量型版本,預設會隨 Visual Studio 一起安裝。
- 使用連接字串按需啟動。
- 專為程式開發而設計。 它會以使用者模式執行,因此沒有複雜的設定。
- 根據預設,系統會在 C:/Users/{user} 目錄中建立 .mdf 檔案。
檢查資料庫
從 [檢視] 功能表中,開啟 [SQL Server 物件總管] (SSOX)。
以滑鼠右鍵按一下 Movie 資料表 > [檢視表設計工具]
請注意 ID 旁的索引鍵圖示。 根據預設,EF 會將名為 ID 的屬性設為主索引鍵。
以滑鼠右鍵按一下 Movie 資料表 > [檢視資料]
初始化資料庫
在 SeedData 資料夾中建立名為 的新類別。 使用下列程式碼取代產生的程式碼:
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using MvcMovie.Data;
using System;
using System.Linq;
namespace MvcMovie.Models
{
public static class SeedData
{
public static void Initialize(IServiceProvider serviceProvider)
{
using (var context = new MvcMovieContext(
serviceProvider.GetRequiredService<
DbContextOptions<MvcMovieContext>>()))
{
// 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; // DB has been seeded.
}
新增種子初始設定式
以下列程式碼取代 Program.cs 的內容:
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using MvcMovie.Data;
using MvcMovie.Models;
using System;
namespace MvcMovie
{
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>();
});
}
}
測試應用程式。
刪除資料庫中的所有記錄。 您可以使用瀏覽器或 SSOX 的刪除連結來執行這項操作。
強制應用程式初始化 (呼叫 Startup 類別中的方法),以執行植入方法。 若要強制初始化,IIS Express 必須停止並重新啟動。 您可以使用下列其中一個方法來執行此工作:
以滑鼠右鍵按一下通知區域中的 IIS Express 系統匣圖示,然後點選 [結束] 或 [停止站台]:
- 如果您已在非偵錯模式中執行 VS,請按 F5 以偵錯模式執行。
- 如果您已在偵錯模式中執行 VS,請停止偵錯工具,然後按 F5。
應用程式會顯示植入的資料。