在 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. 您將會使用移轉,從您的 EF Core 模型建立資料庫。You use migrations to create the database from your EF Core model.

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

必要條件Prerequisites

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

在 Visual Studio 2017 中建立新專案Create a new project in Visual Studio 2017

  • 開啟 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 Core] 和 [ASP.NET Core 2.1] 選項Ensure the options .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
    • 確認 [驗證] 已設為 [無驗證]Ensure that Authentication is set to No Authentication
    • 按一下 [確定] Click OK

警告:如果您針對 [驗證] 使用 [個別使用者帳戶] 而不是 [無],則會將 Entity Framework Core 模型新增至您專案中的 Models\IdentityModel.csWarning: If you use Individual User Accounts instead of None for Authentication then an Entity Framework Core model will be added to your 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 List<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; }
        }
    }
    

在實際的應用程式中,一般會將模型中的每個類別置於不同的檔案中。In a real app you would typically put each class from your model in a separate file. 為了簡單起見,本教學課程將所有類別皆置於同一個檔案中。For the sake of simplicity, this tutorial puts all the classes in one file.

使用相依性插入來註冊內容Register your 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 your MVC controllers) are then provided these services via constructor parameters or properties.

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

  • 開啟 Startup.csOpen Startup.cs

  • 加入下列 using 陳述式:Add the following using statements:

    using EFGetStarted.AspNetCore.NewDb.Models;
    using Microsoft.EntityFrameworkCore;
    

呼叫 AddDbContext 方法,將該內容註冊為服務。Call the AddDbContext method to register the context as a service.

  • 將下列反白顯示的程式碼新增至 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;
    }
    

注意:在實際的應用程式中,一般會將連接字串置於設定檔或環境變數中。Note: A real app would generally 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

一旦有模型之後,就可以使用移轉來建立資料庫。Once you have a model, you can use migrations to create a database.

  • [工具] > [NuGet 套件管理員] > [套件管理員主控台]Tools > NuGet Package Manager > Package Manager Console
  • 執行 Add-Migration InitialCreate 來建立移轉的結構,以針對您的模型建立一組初始的資料表。Run Add-Migration InitialCreate to scaffold a migration to create the initial set of tables for your model. 如果您收到 The term 'add-migration' is not recognized as the name of a cmdlet 的錯誤,請關閉再重新開啟 Visual Studio。If you receive an error stating The term 'add-migration' is not recognized as the name of a cmdlet, close and reopen Visual Studio.
  • 執行 Update-Database 以將新的移轉套用至資料庫。Run Update-Database to apply the new migration to the database. 此命令會建立資料庫,然後才套用移轉。This command creates the database before applying migrations.

建立控制器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.

執行應用程式Run the application

按 F5 來執行和測試應用程式。Press F5 to run and test the app.

  • 巡覽至 /BlogsNavigate to /Blogs
  • 使用建立連結來建立一些部落格項目。Use the create link to create some blog entries. 測試詳細資料和刪除連結。Test the details and delete links.

影像

影像

其他資源Additional Resources