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

提示

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

必要條件Prerequisites

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

建立新專案Create a new project

  • 開啟 Visual StudioOpen Visual Studio

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

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

  • 選取 [主控台應用程式 (.NET Framework)] 專案範本Select the Console App (.NET Framework) 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

稍後在本逐步解說中,我們將使用部分 Entity Framework 工具來維護資料庫。Later in this walkthrough we will also be using some Entity Framework Tools to maintain the database. 因此,我們也將安裝工具套件。So we will install the tools package as well.

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

建立您的模型Create your model

現在就來定義組成模型的內容和實體類別。Now it's time to define a context and entity classes that make up your 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 EFGetStarted.ConsoleApp
{
    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; }
    }
}

提示

在實際的應用程式中,您會將每個類別放在個別的檔案中,然後將連接字串放在 App.Config 檔案中,並使用 ConfigurationManager 來讀取。In a real application you would put each class in a separate file and put the connection string in the App.Config file and read it out using ConfigurationManager. 為了簡單起見,我們在此教學課程中將所有項目都放在單一程式碼檔案中。For the sake of simplicity, we are putting everything in a single code file for this tutorial.

建立您的資料庫Create your database

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

  • [工具] –> [NuGet 套件管理員] –> [套件管理員主控台]Tools –> NuGet Package Manager –> Package Manager Console

  • 執行 Add-Migration MyFirstMigration 來建立移轉的結構,以針對您的模型建立一組初始的資料表。Run Add-Migration MyFirstMigration to scaffold a migration to create the initial set of tables for your model.

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

提示

如果日後要對您的模型進行變更,則可以使用 Add-Migration 命令來建立新移轉的結構,以對資料庫做出相對應的結構描述變更。If you make future changes to your 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 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
{
    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 will see that one blog is saved to the database and then the details of all blogs are printed to the console.

影像