在 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 walkthrough, you will build an ASP.NET Core MVC application that performs basic data access using Entity Framework Core. 您將使用移轉,以便從您的 EF Core 模型來建立資料庫。You will use migrations to create the database from your EF Core model. 如需 Entity Framework Core 的教學課程,請參閱其他資源See Additional Resources for more Entity Framework Core tutorials.

本教學課程需要:This tutorial requires:

提示

您可以在 GitHub 上檢視此文章的範例 (英文)。You can view this article's sample on GitHub.

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

  • [檔案] > [新增] > [專案]File > New > Project
  • 從左側功能表選取 [已安裝] > [範本] > [Visual C#] > [.NET Core]。From the left menu select Installed > Templates > 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.0] 選項Ensure the options .NET Core and ASP.NET Core 2.0 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 will learn in this walkthrough, 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 資料庫提供者來安裝套件。Install the package for the EF Core database provider(s) you want to target. 本逐步解說會使用 SQL Server。This walkthrough uses SQL Server. 如需可用的提供者清單,請參閱資料庫提供者For a list of available providers see Database Providers.

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

  • 執行 Install-Package Microsoft.EntityFrameworkCore.SqlServerRun Install-Package Microsoft.EntityFrameworkCore.SqlServer

我們將使用一些 Entity Framework Core 工具,以便從您的 EF Core 模型來建立資料庫。We will be using some Entity Framework Core Tools to create a database from your EF Core model. 因此,我們也將安裝工具套件:So we will install the tools package as well:

  • 執行 Install-Package Microsoft.EntityFrameworkCore.ToolsRun Install-Package Microsoft.EntityFrameworkCore.Tools

我們將使用一些 ASP.NET Core Scaffolding 工具,於稍後建立控制器與檢視。We will be using some ASP.NET Core Scaffolding tools to create controllers and views later on. 因此,我們也將安裝此設計套件:So we will install this design package as well:

  • 執行 Install-Package Microsoft.VisualStudio.Web.CodeGeneration.DesignRun Install-Package Microsoft.VisualStudio.Web.CodeGeneration.Design

建立模型Create the model

定義組成模型的內容和實體類別:Define a context 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; }
        }
    }
    

注意:在實際的應用程式中,您通常會將模型中的每個類別放在不同的檔案中。Note: In a real app you would typically put each class from your model in a separate file. 為了簡單起見,我們在此教學課程中將所有類別放在同一個檔案中。For the sake of simplicity, we are putting all the classes in one file for this tutorial.

使用相依性插入來註冊內容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,我們要將它註冊為服務。In order for our MVC controllers to make use of BloggingContext we will register it as a service.

  • 開啟 Startup.csOpen Startup.cs

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

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

加入 AddDbContext 方法以將它註冊為服務:Add the AddDbContext method to register it as a service:

  • 將下列程式碼加入 ConfigureServices 方法:Add the following code to the ConfigureServices method:

    // This method gets called by the runtime. Use this method to add services to the container.
    public void ConfigureServices(IServiceCollection services)
    {
        services.AddMvc();
    
        var connection = @"Server=(localdb)\mssqllocaldb;Database=EFGetStarted.AspNetCore.NewDb;Trusted_Connection=True;ConnectRetryCount=0";
        services.AddDbContext<BloggingContext>(options => options.UseSqlServer(connection));
    }
    

注意:實際的應用程式通常會將連接字串放入到設定檔中。Note: A real app would generally put the connection string in a configuration file. 為了簡單起見,我們在程式碼中加以定義。For the sake of simplicity, we are defining it in code. 如需詳細資訊,請參閱連接字串See Connection Strings for more information.

建立您的資料庫Create your database

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

  • 開啟 PMC:Open the PMC:

    [工具] –> [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

在專案中啟用 Scaffolding:Enable scaffolding in the project:

  • 在 [方案總管] 中以滑鼠右鍵按一下 [Controllers] 資料夾,然後選取 [新增] > [控制器]。Right-click on the Controllers folder in Solution Explorer and select Add > Controller.
  • 選取 [基本相依性],然後按一下 [新增]。Select Minimal Dependencies and click Add.
  • 您可以忽略或刪除 ScaffoldingReadMe.txt 檔案。You can ignore or delete the ScaffoldingReadMe.txt file.

啟用 Scaffolding 之後,就可以建立 Blog 實體的控制器結構。Now that scaffolding is enabled, we can scaffold a controller 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 Ok.
  • 將 [模型類別] 設為 [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