在 ASP.NET Core 上使用 EF Core 搭配現有資料庫的使用者入門Getting Started with EF Core on ASP.NET Core with an Existing 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. 您將會對現有的資料庫進行還原工程,建立 Entity Framework 模型。You reverse engineer an existing database to create an Entity Framework model.

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

必要條件Prerequisites

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

建立部落格資料庫Create 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, 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 > Visual C# > Web
  • 選取 [ASP.NET Core Web 應用程式] 專案範本Select the ASP.NET Core Web Application 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
  • 請確定目標架構下拉式清單設定為 .NET Core,然後版本下拉式清單設定為 ASP.NET Core 2.1Make sure that the target framework dropdown is set to .NET Core, and the version dropdown is set to ASP.NET Core 2.1
  • 選取 [Web 應用程式 (模型-檢視-控制器)] 範本Select the Web Application (Model-View-Controller) template
  • 確認 [驗證] 已設為 [無驗證]Ensure that Authentication is set to No Authentication
  • 按一下 [確定] Click OK

安裝 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.

針對您的模型進行反向工程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. 例如,-Tables Blog,PostFor example, -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. 以下為 BlogPost 實體類別:Here are the Blog and Post entity classes:

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 ICollection<Post> Post { get; set; }
    }
}
using System;
using System.Collections.Generic;

namespace EFGetStarted.AspNetCore.ExistingDb.Models
{
    public partial class Post
    {
        public int PostId { get; set; }
        public int BlogId { get; set; }
        public string Content { get; set; }
        public string Title { get; set; }

        public Blog Blog { get; set; }
    }
}

提示

若要啟用延遲載入,可以設定瀏覽屬性 virtual (Blog.Post 與 Post.Blog)。To enable lazy loading, you can make navigation properties virtual (Blog.Post and Post.Blog).

內容代表資料庫的工作階段,並可讓您查詢和儲存實體類別的執行個體。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 BloggingContext()
   {
   }

   public BloggingContext(DbContextOptions<BloggingContext> options)
       : base(options)
   {
   }

   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.

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

若要為 MVC 控制器提供 BloggingContext,請將其註冊為服務。To make BloggingContext available to MVC controllers, 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 you can use the AddDbContext(...) method to register it as a service.

  • 找出 ConfigureServices(...) 方法Locate the ConfigureServices(...) method
  • 新增下列反白顯示的程式碼,將內容註冊為服務Add the following highlighted 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.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=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 or environment variable. 為了簡單起見,本教學課程將會請您將其定義在程式碼中。For the sake of simplicity, this tutorial has you define it in code. 如需詳細資訊,請參閱連接字串For more information, see Connection Strings.

建立控制器和檢視Create a controller and views

  • 在 [方案總管] 中以滑鼠右鍵按一下 [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 builds and opens in a web browser
  • 巡覽至 /BlogsNavigate to /Blogs
  • 按一下 [新建]Click Create New
  • 輸入新部落格的 URL,然後按一下 [建立]Enter a Url for the new blog and click Create

影像

影像