在 ASP.NET Core 上使用 EF Core 搭配現有資料庫的使用者入門Getting Started with EF Core on ASP.NET Core with an Existing Database

重要

.NET Core SDK 已不再支援 project.json 或 Visual Studio 2015。The .NET Core SDK no longer supports project.json or Visual Studio 2015. 針對所有進行 .NET Core 開發的人員,建議從 project.json 移轉至 csprojVisual Studio 2017Everyone doing .NET Core development is encouraged to migrate from project.json to csproj and Visual Studio 2017.

在本逐步解說中,您將建置 ASP.NET Core MVC 應用程式,該應用程式將使用 Entity Framework 執行基本的資料存取。In this walkthrough, you will build an ASP.NET Core MVC application that performs basic data access using Entity Framework. 您將會使用反向工程,根據現有的資料庫來建立 Entity Framework 模型。You will use reverse engineering to create an Entity Framework model based on an existing database.

提示

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

必要條件Prerequisites

若要完成此逐步解說,必須符合下列必要條件:The following prerequisites are needed to complete this walkthrough:

部落格資料庫Blogging database

本教學課程使用您 LocalDb 執行個體上的部落格資料庫作為現有的資料庫。This tutorial uses a Blogging database on your LocalDb instance as the existing database.

提示

如果您在另一個教學課程中已經建立部落格資料庫,則可以跳過這些步驟。If you have already created the Blogging database as part of another tutorial, you can skip these steps.

  • 開啟 Visual StudioOpen Visual Studio
  • [工具] > [連線到資料庫]Tools -> Connect to Database...
  • 選取 [Microsoft SQL Server],並按一下 [繼續]Select Microsoft SQL Server and click Continue
  • 輸入 (localdb)\mssqllocaldb 作為伺服器名稱Enter (localdb)\mssqllocaldb as the Server Name
  • 輸入 master 作為資料庫名稱,並按一下 [確定]Enter master as the Database Name and click OK
  • master 資料庫現在會顯示在 [伺服器總管] 中的 [資料連線] 下The master database is now displayed under Data Connections in Server Explorer
  • 以滑鼠右鍵按一下 [伺服器總管] 中的資料庫,並選取 [新增查詢]Right-click on the database in Server Explorer and select New Query
  • 將下面列出的指令碼複製到查詢編輯器中Copy the script, listed below, into the query editor
  • 以滑鼠右鍵按一下查詢編輯器,然後選取 [執行]Right-click on the query editor and select Execute
CREATE DATABASE [Blogging];
GO

USE [Blogging];
GO

CREATE TABLE [Blog] (
    [BlogId] int NOT NULL IDENTITY,
    [Url] nvarchar(max) NOT NULL,
    CONSTRAINT [PK_Blog] PRIMARY KEY ([BlogId])
);
GO

CREATE TABLE [Post] (
    [PostId] int NOT NULL IDENTITY,
    [BlogId] int NOT NULL,
    [Content] nvarchar(max),
    [Title] nvarchar(max),
    CONSTRAINT [PK_Post] PRIMARY KEY ([PostId]),
    CONSTRAINT [FK_Post_Blog_BlogId] FOREIGN KEY ([BlogId]) REFERENCES [Blog] ([BlogId]) ON DELETE CASCADE
);
GO

INSERT INTO [Blog] (Url) VALUES
('http://blogs.msdn.com/dotnet'),
('http://blogs.msdn.com/webdev'),
('http://blogs.msdn.com/visualstudio')
GO

建立新專案Create a new project

  • 開啟 Visual Studio 2017Open Visual Studio 2017
  • [檔案] > [新增] > [專案]File -> New -> Project...
  • 從左側功能表選取 [已安裝] > [範本] > [Visual C#] > [Web]From the left menu select Installed -> Templates -> Visual C# -> Web
  • 選取 [ASP.NET Core Web 應用程式 (.NET Core)] 專案範本Select the ASP.NET Core Web Application (.NET Core) project template
  • 輸入 EFGetStarted.AspNetCore.ExistingDb 作為名稱,然後按一下 [確定]Enter EFGetStarted.AspNetCore.ExistingDb as the name and click OK
  • 等候 [新增 ASP.NET Core Web 應用程式] 對話方塊出現Wait for the New ASP.NET Core Web Application dialog to appear
  • 在 [ASP.NET Core 範本 2.0] 下,選取 [Web 應用程式 (模型-檢視-控制器)]Under ASP.NET Core Templates 2.0 select the Web Application (Model-View-Controller)
  • 確認 [驗證] 已設為 [無驗證]Ensure that Authentication is set to No Authentication
  • 按一下 [確定] Click OK

安裝 Entity FrameworkInstall Entity Framework

若要使用 EF Core,請針對您要作為目標的資料庫提供者來安裝套件。To use EF Core, install the package for the 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 工具,以便從資料庫來建立模型。We will be using some Entity Framework Tools to create a model from the database. 因此,我們也將安裝工具套件: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

針對您的模型進行反向工程Reverse engineer your model

現在就可以根據您現有的資料庫來建立 EF 模型。Now it's time to create the EF model based on your existing database.

  • [工具] –> [NuGet 套件管理員] –> [套件管理員主控台]Tools –> NuGet Package Manager –> Package Manager Console
  • 執行下列命令,以便從現有的資料庫來建立模型:Run the following command to create a model from the existing database:
Scaffold-DbContext "Server=(localdb)\mssqllocaldb;Database=Blogging;Trusted_Connection=True;" Microsoft.EntityFrameworkCore.SqlServer -OutputDir Models

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

提示

您可以將 -Tables 引數加入上述命令,以指定要為哪些資料表產生實體。You can specify which tables you want to generate entities for by adding the -Tables argument to the command above. 例如E.g. -Tables Blog,Post.-Tables Blog,Post.

反向工程程序會根據現有資料庫的結構描述,建立實體類別 (Blog.cs & Post.cs) 和衍生的內容 (BloggingContext.cs)。The reverse engineer process created entity classes (Blog.cs & Post.cs) and a derived context (BloggingContext.cs) based on the schema of the existing database.

實體類別是簡單的 C# 物件,代表您要查詢和儲存的資料。The entity classes are simple C# objects that represent the data you will be querying and saving.

using System;
using System.Collections.Generic;

namespace EFGetStarted.AspNetCore.ExistingDb.Models
{
    public partial class Blog
    {
        public Blog()
        {
            Post = new HashSet<Post>();
        }

        public int BlogId { get; set; }
        public string Url { get; set; }

        public virtual ICollection<Post> Post { get; set; }
    }
}

內容代表資料庫的工作階段,並可讓您查詢和儲存實體類別的執行個體。The context represents a session with the database and allows you to query and save instances of the entity classes.

public partial class BloggingContext : DbContext
{
   public virtual DbSet<Blog> Blog { get; set; }
   public virtual DbSet<Post> Post { get; set; }

   protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
   {
       if (!optionsBuilder.IsConfigured)
       {
           #warning To protect potentially sensitive information in your connection string, you should move it out of source code. See http://go.microsoft.com/fwlink/?LinkId=723263 for guidance on storing connection strings.
           optionsBuilder.UseSqlServer(@"Server=(localdb)\mssqllocaldb;Database=Blogging;Trusted_Connection=True;");
       }
   }

   protected override void OnModelCreating(ModelBuilder modelBuilder)
   {
       modelBuilder.Entity<Blog>(entity =>
       {
           entity.Property(e => e.Url).IsRequired();
       });

       modelBuilder.Entity<Post>(entity =>
       {
           entity.HasOne(d => d.Blog)
               .WithMany(p => p.Post)
               .HasForeignKey(d => d.BlogId);
       });
   }
}

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

相依性插入的概念是 ASP.NET Core 的核心。The concept of dependency injection is central to ASP.NET Core. 服務 (例如 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. 如需相依性插入的詳細資訊,請參閱 ASP.NET 網站上的相依性插入文章。For more information on dependency injection see the Dependency Injection article on the ASP.NET site.

移除內嵌內容設定Remove inline context configuration

在 ASP.NET Core 中,通常是在 Startup.cs 中執行設定。In ASP.NET Core, configuration is generally performed in Startup.cs. 為了遵循此模式,我們要將資料庫提供者的設定移至 Startup.csTo conform to this pattern, we will move configuration of the database provider to Startup.cs.

  • 開啟 Models\BloggingContext.csOpen Models\BloggingContext.cs
  • 刪除 OnConfiguring(...) 方法Delete the OnConfiguring(...) method
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
    #warning To protect potentially sensitive information in your connection string, you should move it out of source code. See http://go.microsoft.com/fwlink/?LinkId=723263 for guidance on storing connection strings.
    optionsBuilder.UseSqlServer(@"Server=(localdb)\mssqllocaldb;Database=Blogging;Trusted_Connection=True;");
}
  • 新增下列建構函式,以藉由相依性插入將設定傳遞到內容中Add the following constructor, which will allow configuration to be passed into the context by dependency injection
public BloggingContext(DbContextOptions<BloggingContext> options)
    : base(options)
{ }

在 Startup.cs 中註冊並設定內容Register and configure your context in Startup.cs

為了讓 MVC 控制器能使用 BloggingContext,我們要將它註冊為服務。In order for our MVC controllers to make use of BloggingContext we are going to register it as a service.

  • 開啟 Startup.csOpen Startup.cs
  • 在檔案開頭加入下列 using 陳述式Add the following using statements at the start of the file
using EFGetStarted.AspNetCore.ExistingDb.Models;
using Microsoft.EntityFrameworkCore;

現在,我們可以使用 AddDbContext(...) 方法以將它註冊為服務。Now we can use the AddDbContext(...) method to register it as a service.

  • 找出 ConfigureServices(...) 方法Locate the ConfigureServices(...) method
  • 加入下列程式碼以將內容註冊為服務Add the following code to register the context as a service
// 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=Blogging;Trusted_Connection=True;ConnectRetryCount=0";
    services.AddDbContext<BloggingContext>(options => options.UseSqlServer(connection));
}

提示

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

建立控制器Create a controller

接下來,我們將在專案中啟用 Scaffolding。Next, we'll enable scaffolding in our project.

  • 在 [方案總管] 中以滑鼠右鍵按一下 [Controllers] 資料夾,然後選取 [新增] > [控制器]Right-click on the Controllers folder in Solution Explorer and select Add -> Controller...
  • 選取 [完整相依性],然後按一下 [新增]Select Full Dependencies and click Add
  • 在開啟的 ScaffoldingReadMe.txt 檔案中,您可以忽略其中的指示You can ignore the instructions in the ScaffoldingReadMe.txt file that opens

啟用 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

您現在可以執行應用程式來查看運作狀況。You can now run the application to see it in action.

  • [偵錯] > [啟動但不偵錯]Debug -> Start Without Debugging
  • 系統將會建置應用程式並在網頁瀏覽器中開啟The application will build and open in a web browser
  • 巡覽至 /BlogsNavigate to /Blogs
  • 按一下 [新建]Click Create New
  • 輸入新部落格的 URL,然後按一下 [建立]Enter a Url for the new blog and click Create

image

image