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

在本教學課程中,您將會建置主控台應用程式,而其使用 Entity Framework 對 Microsoft SQL Server 資料庫執行基本的資料存取。In this tutorial, you build a console application that performs basic data access against a Microsoft SQL Server database using Entity Framework. 您會對現有的資料庫進行還原工程,以建立 Entity Framework 模型。You create an Entity Framework model by reverse engineering an existing database.

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

必要條件Prerequisites

建立部落格資料庫Create Blogging database

本教學課程使用 LocalDb 執行個體上的部落格資料庫,作為現有的資料庫。This tutorial uses a Blogging database on the 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#] > [Windows Desktop]From the left menu select Installed > Visual C# > Windows Desktop

  • 選取 [主控台應用程式 (.NET Framework)] 專案範本Select the Console App (.NET Framework) project template

  • 請確定專案的目標為 .NET Framework 4.6.1 或更新版本Make sure that the project targets .NET Framework 4.6.1 or later

  • 將專案命名為 ConsoleApp.ExistingDb,然後按一下 [確定]Name the project ConsoleApp.ExistingDb and 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 tutorial 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 Tools 對資料庫進行還原工程。In the next step, you use some Entity Framework Tools to reverse engineer the database. 因此,也請安裝工具套件。So install the tools package as well.

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

對模型進行還原工程Reverse engineer the model

現在就可以根據您現有的資料庫來建立 EF 模型。Now it's time to create the EF model based on an 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
    

提示

您可以將 -Tables 引數新增至上述命令,以指定要為哪些資料表產生實體。You can specify the tables to generate entities for by adding the -Tables argument to the command above. 例如,-Tables Blog,PostFor example, -Tables Blog,Post.

還原工程處理序會根據現有資料庫的結構描述,建立實體類別 (BlogPost) 與衍生的內容 (BloggingContext)。The reverse engineer process created entity classes (Blog and Post) and a derived context (BloggingContext) 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 ConsoleApp.ExistingDb
{
    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 ConsoleApp.ExistingDb
{
    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. 其備有多種您可用於查詢及儲存實體類別執行個體的方法。It has methods that you can use to query and save instances of the entity classes.

using System;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Metadata;

namespace ConsoleApp.ExistingDb
{
    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);
            });
        }
    }
}

使用模型Use the model

您現已可使用模型來執行資料存取。You can now use the model to perform data access.

  • 開啟 Program.csOpen Program.cs

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

    using System;
    
    namespace ConsoleApp.ExistingDb
    {
        class Program
        {
            static void Main(string[] args)
            {
                using (var db = new BloggingContext())
                {
                    db.Blog.Add(new Blog { Url = "http://blogs.msdn.com/adonet" });
                    var count = db.SaveChanges();
                    Console.WriteLine("{0} records saved to database", count);
    
                    Console.WriteLine();
                    Console.WriteLine("All blogs in database:");
                    foreach (var blog in db.Blog)
                    {
                        Console.WriteLine(" - {0}", blog.Url);
                    }
                }
            }
        }
    }
    
  • 偵錯 > 啟動但不偵錯Debug > Start Without Debugging

    您會看到有一個部落格儲存至資料庫,然後所有部落格的詳細資料皆會列印至主控台。You see that one blog is saved to the database and then the details of all blogs are printed to the console.

    影像

其他資源Additional Resources