第五部分,在 ASP.NET Core MVC 應用程式中操作資料庫

注意

這不是這篇文章的最新版本。 關於目前版本,請參閱本文的 .NET 11 版本。

簡介

本教學系列的這一部分著重於在 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) > 檢視設計師

右鍵點擊電影表 > 檢視設計器。

Designer 開啟了電影桌。

請注意 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 重新啟動。

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

MVC 電影應用程式在 Microsoft Edge 中開啟,顯示電影資料。

重新整理 Movie 表格時,資料依然相同。

電影表有種子資料。

注意

您可能無法在小數欄位中輸入小數逗號。 若要在使用逗號 (",") 作為小數點的非英文地區設定及非美式英文日期格式中支援 jQuery 驗證,您必須採取將應用程式全球化的步驟。 請參考這則 GitHub 留言 4076,了解如何加入小數逗號。