在 .NET Framework 上使用 EF Core 搭配新資料庫的使用者入門Getting started with EF Core on .NET Framework with a New 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. 您會使用移轉從模型建立資料庫。You use migrations to create the database from a model.

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

必要條件Prerequisites

建立新專案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.NewDb,然後按一下 [確定]Name the project ConsoleApp.NewDb 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 工具,來維護該資料庫。Later in this tutorial you use some Entity Framework Tools to maintain the database. 因此,也請安裝工具套件。So install the tools package as well.

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

建立模型Create the model

您現已可定義組成模型的內容與實體類別。Now it's time to define a context and entity classes that make up the model.

  • [專案] > [新增類別...]Project > 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 ConsoleApp.NewDb
    {
        public class BloggingContext : DbContext
        {
            public DbSet<Blog> Blogs { get; set; }
            public DbSet<Post> Posts { get; set; }
    
            protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
            {
                optionsBuilder.UseSqlServer(@"Server=(localdb)\mssqllocaldb;Database=EFGetStarted.ConsoleApp.NewDb;Trusted_Connection=True;");
            }
        }
    
        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; }
        }
    }
    

提示

在實際的應用程式中,要將每個類別置於不同的檔案中,然後將連接字串置於組態檔或環境變數中。In a real application you would put each class in a separate file and put the connection string in a configuration file or environment variable. 為了簡單起見,在本教學課程中會將所有項目都置於單一個程式碼檔案中。For the sake of simplicity, everything is in a single code file for this tutorial.

建立資料庫Create the database

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

  • [工具] > [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 the model.

  • 執行 Update-Database 以將新的移轉套用至資料庫。Run Update-Database to apply the new migration to the database. 因為您的資料庫尚未存在,因此會在套用移轉之前為您建立。Because the database doesn't exist yet, it will be created before the migration is applied.

提示

若您變更了您的模型,則可使用 Add-Migration 命令來建立新移轉的結構,以對資料庫做出相對應的結構描述變更。If you make changes to the model, you can use the Add-Migration command to scaffold a new migration to make the corresponding schema changes to the database. 檢查完已建立結構的程式碼之後 (並進行任何必要的變更),就可以使用 Update-Database 命令將變更套用至資料庫。Once you have checked the scaffolded code (and made any required changes), you can use the Update-Database command to apply the changes to the database.

EF 在資料庫中使用 __EFMigrationsHistory 資料表,以確認已經套用至資料庫的移轉。EF uses a __EFMigrationsHistory table in the database to keep track of which migrations have already been applied to the database.

使用模型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.NewDb
    {
        class Program
        {
            static void Main(string[] args)
            {
                using (var db = new BloggingContext())
                {
                    db.Blogs.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.Blogs)
                    {
                        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