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

在本逐步解說中,您將建置主控台應用程式,該應用程式將使用 Entity Framework 對 Microsoft SQL Server 資料庫執行基本資料存取。In this walkthrough, you will build a console application that performs basic data access against a Microsoft SQL Server database 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 StudioOpen Visual Studio

  • [檔案] > [新增] > [專案]...File > New > Project...

  • 從左側功能表選取 [範本] > [Visual C#] > [Windows]From the left menu select Templates > Visual C# > Windows

  • 選取 [主控台應用程式] 專案範本Select the Console Application project template

  • 請確認您的目標是 .NET Framework 4.5.1 或更新版本Ensure you are targeting .NET Framework 4.5.1 or later

  • 提供專案名稱,然後按一下 [確定]Give the project a name 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 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

為了要從現有的資料庫啟用反向工程,我們也需要安裝幾個其他的套件。To enable reverse engineering from an existing database we need to install a couple of other packages too.

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

針對您的模型進行反向工程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

反向工程程序會根據現有資料庫的結構描述,建立實體類別和衍生的內容。The reverse engineer process created entity classes and a derived context 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.ConsoleApp.ExistingDb
{
    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.

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

namespace EFGetStarted.ConsoleApp.ExistingDb
{
    public partial class BloggingContext : DbContext
    {
        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;");
        }

        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);
            });
        }

        public virtual DbSet<Blog> Blog { get; set; }
        public virtual DbSet<Post> Post { get; set; }
    }
}

使用您的模型Use your model

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

  • 開啟 Program.csOpen Program.cs

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

using System;

namespace EFGetStarted.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 will see that one blog is saved to the database and then the details of all blogs are printed to the console.

影像