注意
這不是這篇文章的最新版本。 關於目前版本,請參閱本文的 .NET 10 版本。
警告
此版本的 ASP.NET Core 已不再支援。 欲了解更多資訊,請參閱.NET及.NET核心支援政策。 關於目前版本,請參閱本文的 .NET 10 版本。
簡介
本教學系列的這一部分著重於在 ASP.NET Core MVC 應用程式中使用 SQL 資料庫。
您將了解如何:
- 註冊並設定 ASP.NET Core MVC 應用程式的 Entity Framework Core 資料庫上下文。
- 在本地開發時使用資料庫連線字串。
- 使用 SQL Server Express LocalDB 進行開發,並使用 SQL Server 物件總管 檢視資料庫與資料。
- 先用初始樣本資料為資料庫做種子。
先決條件
這個教學使用了你在前一步設置的資料庫:Part 4,將模型加入 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 Configuration系統讀取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 檔案。
檢查資料庫
從 View 選單中,開啟 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?}")
.WithStaticAssets();
app.Run();
測試應用程式。 強制應用程式初始化,呼叫 Program.cs 檔案中的程式碼,讓種子方法執行。 要強制初始化,請關閉 Visual Studio 開啟的命令提示字元視窗,然後按 Ctrl+F5 重新啟動。
應用程式會顯示植入的資料。
重新整理 Movie 表格時,資料依然相同。
注意
您可能無法在小數欄位中輸入小數逗號。 若要在使用逗號 (",") 作為小數點的非英文地區設定及非美式英文日期格式中支援 jQuery 驗證,您必須採取將應用程式全球化的步驟。 請參考這則GitHub留言 4076 以獲得如何加入小數點逗號的說明。
簡介
本教學系列的這一部分著重於在 ASP.NET Core MVC 應用程式中使用 SQL 資料庫。
您將了解如何:
- 註冊並設定 ASP.NET Core MVC 應用程式的 Entity Framework Core 資料庫上下文。
- 在本地開發時使用資料庫連線字串。
- 使用 SQL Server Express LocalDB 進行開發,並使用 SQL Server 物件總管 檢視資料庫與資料。
- 先用初始樣本資料為資料庫做種子。
先決條件
這個教學使用了你在前一步設置的資料庫:Part 4,將模型加入 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 Configuration系統讀取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 檔案。
檢查資料庫
從 View 選單中,開啟 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 重新啟動。
應用程式會顯示植入的資料。
注意
您可能無法在小數欄位中輸入小數逗號。 若要在使用逗號 (",") 作為小數點的非英文地區設定及非美式英文日期格式中支援 jQuery 驗證,您必須採取將應用程式全球化的步驟。 請參考這則GitHub留言 4076 以獲得如何加入小數點逗號的說明。
簡介
本教學系列的這一部分著重於在 ASP.NET Core MVC 應用程式中使用 SQL 資料庫。
您將了解如何:
- 註冊並設定 ASP.NET Core MVC 應用程式的 Entity Framework Core 資料庫上下文。
- 在本地開發時使用資料庫連線字串。
- 使用 SQL Server Express LocalDB 進行開發,並使用 SQL Server 物件總管 檢視資料庫與資料。
- 先用初始樣本資料為資料庫做種子。
先決條件
這個教學使用了你在前一步設置的資料庫:Part 4,將模型加入 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 Configuration系統讀取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 檔案。
檢查資料庫
從 View 選單中,開啟 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 重新啟動。
應用程式會顯示植入的資料。
注意
您可能無法在小數欄位中輸入小數逗號。 若要在使用逗號 (",") 作為小數點的非英文地區設定及非美式英文日期格式中支援 jQuery 驗證,您必須採取將應用程式全球化的步驟。 請參考這則GitHub留言 4076 以獲得如何加入小數點逗號的說明。
簡介
本教學系列的這一部分著重於在 ASP.NET Core MVC 應用程式中使用 SQL 資料庫。
您將了解如何:
- 註冊並設定 ASP.NET Core MVC 應用程式的 Entity Framework Core 資料庫上下文。
- 在本地開發時使用資料庫連線字串。
- 使用 SQL Server Express LocalDB 進行開發,並使用 SQL Server 物件總管 檢視資料庫與資料。
- 先用初始樣本資料為資料庫做種子。
先決條件
這個教學使用了你在前一步設置的資料庫:Part 4,將模型加入 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 Configuration系統讀取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 檔案。
檢查資料庫
從 View 選單中,開啟 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 重新啟動。
應用程式會顯示植入的資料。
注意
您可能無法在小數欄位中輸入小數逗號。 若要在使用逗號 (",") 作為小數點的非英文地區設定及非美式英文日期格式中支援 jQuery 驗證,您必須採取將應用程式全球化的步驟。 請參考這則GitHub留言 4076 以獲得如何加入小數點逗號的說明。
簡介
本教學系列的這一部分著重於在 ASP.NET Core MVC 應用程式中使用 SQL 資料庫。
您將了解如何:
- 註冊並設定 ASP.NET Core MVC 應用程式的 Entity Framework Core 資料庫上下文。
- 在本地開發時使用資料庫連線字串。
- 使用 SQL Server Express LocalDB 進行開發,並使用 SQL Server 物件總管 檢視資料庫與資料。
- 先用初始樣本資料為資料庫做種子。
先決條件
這個教學使用了你在前一步設置的資料庫:Part 4,將模型加入 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 Configuration系統讀取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 重新啟動。
應用程式會顯示植入的資料。
注意
您可能無法在小數欄位中輸入小數逗號。 若要在使用逗號 (",") 作為小數點的非英文地區設定及非美式英文日期格式中支援 jQuery 驗證,您必須採取將應用程式全球化的步驟。 請參考這則GitHub留言 4076 以獲得如何加入小數點逗號的說明。
簡介
本教學系列的這一部分著重於在 ASP.NET Core MVC 應用程式中使用 SQL 資料庫。
您將了解如何:
- 註冊並設定 ASP.NET Core MVC 應用程式的 Entity Framework Core 資料庫上下文。
- 在本地開發時使用資料庫連線字串。
- 使用 SQL Server Express LocalDB 進行開發,並使用 SQL Server 物件總管 檢視資料庫與資料。
- 先用初始樣本資料為資料庫做種子。
先決條件
這個教學使用了你在前一步設置的資料庫:Part 4,將模型加入 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 Configuration系統讀取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 檔案。
檢查資料庫
從 View 選單中,開啟 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。
應用程式會顯示植入的資料。
注意
您可能無法在小數欄位中輸入小數逗號。 若要在使用逗號 (",") 作為小數點的非英文地區設定及非美式英文日期格式中支援 jQuery 驗證,您必須採取將應用程式全球化的步驟。 請參考這則GitHub留言 4076 以獲得如何加入小數點逗號的說明。