在 ASP.NET Core 上使用 EF Core 搭配新資料庫的使用者入門Getting Started with EF Core on ASP.NET Core with a New database

在本教學課程中,您將會建置 ASP.NET Core MVC 應用程式,而其使用 Entity Framework Core 執行基本的資料存取。In this tutorial, you build an ASP.NET Core MVC application that performs basic data access using Entity Framework Core. 本教學課程會使用移轉以從資料模型建立資料庫。The tutorial uses migrations to create the database from the data model.

若要遵循本教學課程,您可以在 Windows 上使用 Visual Studio 2017 或在 Windows、macOS 或 Linux 上使用 .NET Core CLI。You can follow the tutorial by using Visual Studio 2017 on Windows, or by using the .NET Core CLI on Windows, macOS, or Linux.

在 GitHub 上檢視此文章的範例:View this article's sample on GitHub:

必要條件Prerequisites

安裝下列軟體:Install the following software:

建立新專案Create a new project

  • 開啟 Visual Studio 2017Open Visual Studio 2017
  • [檔案] > [新增] > [專案]File > New > Project
  • 從左側功能表選取 [已安裝] > [Visual C#] > [.NET Core]。From the left menu, select Installed > Visual C# > .NET Core.
  • 選取 [ASP.NET Core Web 應用程式]。Select ASP.NET Core Web Application.
  • 輸入 EFGetStarted.AspNetCore.NewDb 作為名稱,然後按一下 [確定]。Enter EFGetStarted.AspNetCore.NewDb for the name and click OK.
  • 在 [新增 ASP.NET Core Web 應用程式] 對話方塊中:In the New ASP.NET Core Web Application dialog:
    • 確認下拉式清單中已選取 NET CoreASP.NET Core 2.1 選項Make sure that .NET Core and ASP.NET Core 2.1 are selected in the drop-down lists
    • 選取 [Web 應用程式 (模型-檢視-控制器)] 專案範本Select the Web Application (Model-View-Controller) project template
    • 確認 [驗證] 已設為 [無任何驗證]Make sure that Authentication is set to No Authentication
    • 按一下 [確定] Click OK

警告:如果您針對 [驗證] 使用 [個別使用者帳戶] 而不是 [無],則系統會將 Entity Framework Core 模型新增至 Models\IdentityModel.cs 中的專案。Warning: If you use Individual User Accounts instead of None for Authentication then an Entity Framework Core model will be added to the project in Models\IdentityModel.cs. 您可利用在本教學課程中所學到的技術,選擇新增第二個模型,或是擴充此現有模型以包含您的實體類別。Using the techniques you learn in this tutorial, you can choose to add a second model, or extend this existing model to contain your entity classes.

安裝 Entity Framework CoreInstall Entity Framework Core

若要安裝 EF Core,請為希望作為目標的 EF Core 資料庫提供者,安裝此套件。To install EF Core, you install the package for the EF Core database provider(s) you want to target. 如需可用的提供者清單,請參閱資料庫提供者For a list of available providers, see Database Providers.

在本教學課程中,因為使用 SQL Server,所以無需安裝提供者套件。For this tutorial, you don't have to install a provider package because the tutorial uses SQL Server. Microsoft.AspnetCore.App 中繼套件包含 SQL Server 提供者套件。The SQL Server provider package is included in the Microsoft.AspnetCore.App metapackage.

建立模型Create the model

定義組成模型的內容類別與實體類別。Define a context class and entity classes that make up the model.

  • 以滑鼠右鍵按一下 [Models] 資料夾,然後選取 [新增] > [類別]。Right-click on the Models folder and select Add > Class.

  • 輸入 Model.cs 作為名稱,然後按一下 [確定]。Enter Model.cs as the name and click OK.

  • 以下列程式碼取代檔案的內容:Replace the contents of the file with the following code:

    using Microsoft.EntityFrameworkCore;
    using System.Collections.Generic;
    
    namespace EFGetStarted.AspNetCore.NewDb.Models
    {
        public class BloggingContext : DbContext
        {
            public BloggingContext(DbContextOptions<BloggingContext> options)
                : base(options)
            { }
    
            public DbSet<Blog> Blogs { get; set; }
            public DbSet<Post> Posts { get; set; }
        }
    
        public class Blog
        {
            public int BlogId { get; set; }
            public string Url { get; set; }
    
            public ICollection<Post> Posts { get; set; }
        }
    
        public class Post
        {
            public int PostId { get; set; }
            public string Title { get; set; }
            public string Content { get; set; }
    
            public int BlogId { get; set; }
            public Blog Blog { get; set; }
        }
    }
    

生產環境應用程式通常會將每個類別放在不同的檔案中。A production app would typically put each class in a separate file. 為了簡單起見,本教學課程會將這些類別置於同一個檔案中。For the sake of simplicity, this tutorial puts these classes in one file.

使用相依性插入來註冊內容Register the context with dependency injection

服務 (例如 BloggingContext) 是在應用程式啟動期間使用相依性插入來註冊。Services (such as BloggingContext) are registered with dependency injection during application startup. 接著,系統會透過建構函式參數或屬性,將這些服務提供給需要的元件 (例如 MVC 控制器)。Components that require these services (such as MVC controllers) are provided these services via constructor parameters or properties.

若要為 MVC 控制器提供 BloggingContext,請將其註冊為服務。To make BloggingContext available to MVC controllers, register it as a service.

  • Startup.cs 中,新增下列 using 陳述式:In Startup.cs add the following using statements:

    using EFGetStarted.AspNetCore.NewDb.Models;
    using Microsoft.EntityFrameworkCore;
    
  • 將下列反白顯示的程式碼新增至 ConfigureServices 方法:Add the following highlighted code to the ConfigureServices method:

    public void ConfigureServices(IServiceCollection services)
    {
        services.Configure<CookiePolicyOptions>(options =>
        {
            // This lambda determines whether user consent for non-essential cookies is needed for a given request.
            options.CheckConsentNeeded = context => true;
            options.MinimumSameSitePolicy = SameSiteMode.None;
        });
    
        services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
    
        var connection = @"Server=(localdb)\mssqllocaldb;Database=EFGetStarted.AspNetCore.NewDb;Trusted_Connection=True;ConnectRetryCount=0";
        services.AddDbContext<BloggingContext>
            (options => options.UseSqlServer(connection));
        // BloggingContext requires
        // using EFGetStarted.AspNetCore.NewDb.Models;
        // UseSqlServer requires
        // using Microsoft.EntityFrameworkCore;
    }
    

生產環境應用程式一般會將連接字串放在設定檔或環境變數中。A production app would typically put the connection string in a configuration file or environment variable. 為了簡單起見,本教學課程將其定義在程式碼中。For the sake of simplicity, this tutorial defines it in code. 如需詳細資訊,請參閱連接字串See Connection Strings for more information.

建立資料庫Create the database

下列步驟會使用移轉來建立資料庫。The following steps use migrations to create a database.

  • [工具] > [NuGet 套件管理員] > [套件管理員主控台]Tools > NuGet Package Manager > Package Manager Console

  • 執行下列命令:Run the following commands:

    Add-Migration InitialCreate
    Update-Database
    

    如果您收到 The term 'add-migration' is not recognized as the name of a cmdlet 的錯誤,請關閉再重新開啟 Visual Studio。If you get an error stating The term 'add-migration' is not recognized as the name of a cmdlet, close and reopen Visual Studio.

    Add-Migration 命令會建立移轉的 Scaffolding,以針對模型建立一組初始資料表。The Add-Migration command scaffolds a migration to create the initial set of tables for the model. Update-Database 命令會建立資料庫,並對資料庫套用新的移轉。The Update-Database command creates the database and applies the new migration to it.

建立控制器Create a controller

Blog 實體設定控制器與檢視的結構。Scaffold a controller and views for the Blog entity.

  • 在 [方案總管] 中以滑鼠右鍵按一下 [Controllers] 資料夾,然後選取 [新增] > [控制器]。Right-click on the Controllers folder in Solution Explorer and select Add > Controller.
  • 選取 [使用 Entity Framework 執行檢視的 MVC 控制器],然後按一下 [新增]。Select MVC Controller with views, using Entity Framework and click Add.
  • 將 [模型類別] 設為 [Blog],並將 [資料內容類別] 設為 [BloggingContext]。Set Model class to Blog and Data context class to BloggingContext.
  • 按一下 [加入] 。Click Add.

Scaffolding 引擎會建立下列檔案:The scaffolding engine creates the following files:

  • 控制器 (Controllers/BlogsController.cs)A controller (Controllers/BlogsController.cs)
  • [建立]、[刪除]、[詳細資料]、[編輯] 和 [索引] 頁面的 Razor 檢視 (Views/Movies/*.cshtml)Razor views for Create, Delete, Details, Edit, and Index pages (Views/Movies/*.cshtml)

執行應用程式Run the application

  • 偵錯 > 啟動但不偵錯Debug > Start Without Debugging
  • 巡覽至 /BlogsNavigate to /Blogs

  • 使用 [建立新項目] 連結來建立一些部落格項目。Use the Create New link to create some blog entries.

    建立頁面

  • 測試 [詳細資料]、[編輯] 和 [刪除] 連結。Test the Details, Edit, and Delete links.

    索引頁面

其他資源Additional Resources