第 5 部分,在 ASP.NET Core MVC 應用程式中使用資料庫

注意

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

重要

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

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

作者:Rick AndersonJon P Smith

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 的連接字串。 如需詳細資訊,請參閱組態

SQL Server Express LocalDB

LocalDB:

  • 這是 SQL Server Express 資料庫引擎的輕量型版本,預設會隨 Visual Studio 一起安裝。
  • 使用連接字串視需要啟動。
  • 以程式開發為目標。 它會以使用者模式執行,因此沒有複雜的設定。
  • 根據預設,系統會在 C:/Users/{user} 目錄中建立 .mdf 檔案。

檢查資料庫

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

以滑鼠右鍵按一下 Movie 資料表 (dbo.Movie) > [檢視表設計工具]

以滑鼠右鍵按一下 [電影] 資料表 > [檢視表設計工具]。

在設計工具中開啟電影資料表

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

以滑鼠右鍵按一下 Movie 資料表 > [檢視資料]

以滑鼠右鍵按一下 [電影] 資料表 > [檢視資料]。

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

植入資料庫

Models 資料夾中建立名為 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 重新啟動。

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

在 Microsoft Edge 中開啟 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 的連接字串。 如需詳細資訊,請參閱組態

SQL Server Express LocalDB

LocalDB:

  • 這是 SQL Server Express 資料庫引擎的輕量型版本,預設會隨 Visual Studio 一起安裝。
  • 使用連接字串視需要啟動。
  • 以程式開發為目標。 它會以使用者模式執行,因此沒有複雜的設定。
  • 根據預設,系統會在 C:/Users/{user} 目錄中建立 .mdf 檔案。

檢查資料庫

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

以滑鼠右鍵按一下 Movie 資料表 (dbo.Movie) > [檢視表設計工具]

以滑鼠右鍵按一下 [電影] 資料表 > [檢視表設計工具]。

在設計工具中開啟電影資料表

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

以滑鼠右鍵按一下 Movie 資料表 > [檢視資料]

以滑鼠右鍵按一下 [電影] 資料表 > [檢視資料]。

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

植入資料庫

Models 資料夾中建立名為 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 重新啟動。

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

在 Microsoft Edge 中開啟 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 的連接字串。 如需詳細資訊,請參閱組態

SQL Server Express LocalDB

LocalDB:

  • 這是 SQL Server Express 資料庫引擎的輕量型版本,預設會隨 Visual Studio 一起安裝。
  • 使用連接字串視需要啟動。
  • 以程式開發為目標。 它會以使用者模式執行,因此沒有複雜的設定。
  • 根據預設,系統會在 C:/Users/{user} 目錄中建立 .mdf 檔案。

植入資料庫

Models 資料夾中建立名為 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 重新啟動。

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

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

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

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 的連接字串。 如需詳細資訊,請參閱組態

SQL Server Express LocalDB

LocalDB:

  • 這是 SQL Server Express 資料庫引擎的輕量型版本,預設會隨 Visual Studio 一起安裝。
  • 使用連接字串視需要啟動。
  • 以程式開發為目標。 它會以使用者模式執行,因此沒有複雜的設定。
  • 根據預設,系統會在 C:/Users/{user} 目錄中建立 .mdf 檔案。

檢查資料庫

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

檢視功能表

以滑鼠右鍵按一下 Movie 資料表 > [檢視表設計工具]

以滑鼠右鍵按一下 [電影] 資料表 > [檢視表設計工具]

在設計工具中開啟電影資料表

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

以滑鼠右鍵按一下 Movie 資料表 > [檢視資料]

以滑鼠右鍵按一下 [電影] 資料表 > [檢視資料]

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

植入資料庫

Models 資料夾中建立名為 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 系統匣圖示,然後點選 [結束] 或 [停止站台]

    IIS Express 系統匣圖示

    操作功能表

    • 如果您已在非偵錯模式中執行 VS,請按 F5 以偵錯模式執行。
    • 如果您已在偵錯模式中執行 VS,請停止偵錯工具,然後按 F5。

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

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