Entity Framework Core 工具的參考-Visual Studio 中的套件管理員主控台Entity Framework Core tools reference - Package Manager Console in Visual Studio

Entity Framework Core 套件管理員主控台 (PMC) 工具會執行設計階段開發工作。The Package Manager Console (PMC) tools for Entity Framework Core perform design-time development tasks. 例如,建立移轉、 套用移轉,並產生程式碼在現有的資料庫為基礎的模型。For example, they create migrations, apply migrations, and generate code for a model based on an existing database. 使用 Visual Studio 內執行的命令Package Manager ConsoleThe commands run inside of Visual Studio using the Package Manager Console. 這些工具會使用 .NET Framework 和 .NET Core 專案。These tools work with both .NET Framework and .NET Core projects.

如果您未使用 Visual Studio,我們建議您EF Core 命令列工具改。If you aren't using Visual Studio, we recommend the EF Core Command-line Tools instead. CLI 工具是跨平台和在命令提示字元內執行。The CLI tools are cross-platform and run inside a command prompt.

安裝工具Installing the tools

安裝和更新工具的程序是根據 ASP.NET Core 2.1 + 和更早版本或其他專案類型而不同。The procedures for installing and updating the tools differ between ASP.NET Core 2.1+ and earlier versions or other project types.

ASP.NET Core 2.1 和更新版本ASP.NET Core version 2.1 and later

工具會自動包含在 ASP.NET Core 2.1 + 專案因為Microsoft.EntityFrameworkCore.Tools套件包含在Microsoft.AspNetCore.App 中繼套件The tools are automatically included in an ASP.NET Core 2.1+ project because the Microsoft.EntityFrameworkCore.Tools package is included in the Microsoft.AspNetCore.App metapackage.

因此,您不必採取任何動作來安裝工具,但您需要:Therefore, you don't have to do anything to install the tools, but you do have to:

  • 新的專案中使用工具之前先還原套件。Restore packages before using the tools in a new project.
  • 將封裝安裝到更新為較新版本的工具。Install a package to update the tools to a newer version.

若要確定您取得最新版本的工具,我們建議,您也可以下列步驟:To make sure that you're getting the latest version of the tools, we recommend that you also do the following step:

  • 編輯您 .csproj檔案,並新增一行,指定最新版Microsoft.EntityFrameworkCore.Tools封裝。Edit your .csproj file and add a line specifying the latest version of the Microsoft.EntityFrameworkCore.Tools package. 例如, .csproj檔案可能包含ItemGroup看起來像這樣:For example, the .csproj file might include an ItemGroup that looks like this:

    <ItemGroup>
      <PackageReference Include="Microsoft.AspNetCore.App" />
      <PackageReference Include="Microsoft.EntityFrameworkCore.Tools" Version="2.1.3" />
      <PackageReference Include="Microsoft.VisualStudio.Web.CodeGeneration.Design" Version="2.1.1" />
    </ItemGroup>
    

更新工具,當您收到訊息,如下列範例所示:Update the tools when you get a message like the following example:

EF Core 工具版本 '2.1.1-rtm-30846' 會超過執行階段 '2.1.3-rtm-32065'。The EF Core tools version '2.1.1-rtm-30846' is older than that of the runtime '2.1.3-rtm-32065'. 更新適用於最新的功能和 bug 修正的工具。Update the tools for the latest features and bug fixes.

若要更新的工具:To update the tools:

  • 安裝最新的.NET Core SDK。Install the latest .NET Core SDK.
  • Visual Studio 更新為最新版本。Update Visual Studio to the latest version.
  • 編輯 .csproj檔案使其包含最新的工具套件的套件參考,如先前所示。Edit the .csproj file so that it includes a package reference to the latest tools package, as shown earlier.

其他版本和專案類型Other versions and project types

在中執行下列命令安裝套件管理員主控台工具Package Manager Console:Install the Package Manager Console tools by running the following command in Package Manager Console:

Install-Package Microsoft.EntityFrameworkCore.Tools

在中執行下列命令更新工具Package Manager ConsoleUpdate the tools by running the following command in Package Manager Console.

Update-Package Microsoft.EntityFrameworkCore.Tools

確認安裝Verify the installation

確認安裝工具時,則執行下列命令:Verify that the tools are installed by running this command:

Get-Help about_EntityFrameworkCore

輸出看起來像這樣 (它不會告訴您正在使用的工具版本):The output looks like this (it doesn't tell you which version of the tools you're using):


                     _/\__
               ---==/    \\
         ___  ___   |.    \|\
        | __|| __|  |  )   \\\
        | _| | _|   \_/ |  //|\\
        |___||_|       /   \\\/\\

TOPIC
    about_EntityFrameworkCore

SHORT DESCRIPTION
    Provides information about the Entity Framework Core Package Manager Console Tools.

<A list of available commands follows, omitted here.>

使用的工具Using the tools

之前使用的工具:Before using the tools:

  • 了解目標和啟動專案之間的差異。Understand the difference between target and startup project.
  • 了解如何使用.NET Standard 類別庫的工具。Learn how to use the tools with .NET Standard class libraries.
  • 針對 ASP.NET Core 專案,設定環境。For ASP.NET Core projects, set the environment.

目標和啟動專案Target and startup project

命令是指專案啟始專案The commands refer to a project and a startup project.

  • 專案也稱為目標專案因為它是命令新增或移除檔案的位置。The project is also known as the target project because it's where the commands add or remove files. 根據預設,預設專案中選取Package Manager Console是目標專案。By default, the Default project selected in Package Manager Console is the target project. 您也可以使用為目標的專案指定不同的專案 --project 選項。You can specify a different project as target project by using the --project option.

  • 啟始專案是指的工具建置和執行。The startup project is the one that the tools build and run. 工具必須執行的應用程式程式碼,在設計階段,以取得專案中,例如資料庫連接字串和設定模型的相關資訊。The tools have to execute application code at design time to get information about the project, such as the database connection string and the configuration of the model. 根據預設,啟始專案方案總管 中是啟始專案。By default, the Startup Project in Solution Explorer is the startup project. 您也可以使用為啟始專案指定不同的專案 --startup-project 選項。You can specify a different project as startup project by using the --startup-project option.

啟始專案和目標專案通常是相同的專案。The startup project and target project are often the same project. 典型的案例,其中兩者就會不同的專案時:A typical scenario where they are separate projects is when:

  • EF Core 內容和實體類別是.NET Core 類別庫中。The EF Core context and entity classes are in a .NET Core class library.
  • .NET Core 主控台應用程式或 web 應用程式參考類別庫。A .NET Core console app or web app references the class library.

它也可移轉程式碼置於不同於 EF Core 內容的類別庫It's also possible to put migrations code in a class library separate from the EF Core context.

其他的目標架構Other target frameworks

套件管理員主控台工具會使用.NET Core 或.NET Framework 的專案。The Package Manager Console tools work with .NET Core or .NET Framework projects. .NET Standard 類別庫中有 EF Core 模型的應用程式可能沒有將.NET Core 或.NET Framework 專案。Apps that have the EF Core model in a .NET Standard class library might not have a .NET Core or .NET Framework project. 比方說,這是 Xamarin 與通用 Windows 平台的應用程式,則為 true。For example, this is true of Xamarin and Universal Windows Platform apps. 在此情況下,您可以建立.NET Core 或.NET Framework 主控台應用程式專案的唯一目的是要做為啟始專案的工具。In such cases, you can create a .NET Core or .NET Framework console app project whose only purpose is to act as startup project for the tools. 專案可以是使用實際沒有程式碼的虛設專案—只需要用它來提供這項工具的目標。The project can be a dummy project with no real code — it is only needed to provide a target for the tooling.

為何需要一個 dummy 專案?Why is a dummy project required? 如先前所述,這些工具必須在設計階段中執行應用程式程式碼。As mentioned earlier, the tools have to execute application code at design time. 若要這樣做,請他們需要使用.NET Core 或.NET Framework 執行階段。To do that, they need to use the .NET Core or .NET Framework runtime. .NET Core 或.NET Framework 為目標的專案中的 EF Core 模型時,EF Core 工具會借用從專案的執行階段。When the EF Core model is in a project that targets .NET Core or .NET Framework, the EF Core tools borrow the runtime from the project. 如果是.NET Standard 類別庫中的 EF Core 模型,它們不能這麼做。They can't do that if the EF Core model is in a .NET Standard class library. .NET Standard 並不是實際的.NET 實作;它是一組.NET 實作必須支援的 Api 的規格。The .NET Standard is not an actual .NET implementation; it's a specification of a set of APIs that .NET implementations must support. 因此.NET Standard 是不夠的 EF Core 工具來執行應用程式程式碼。Therefore .NET Standard is not sufficient for the EF Core tools to execute application code. 您建立來做為啟始專案的虛設專案提供具體的目標平台工具可以在其中載入.NET Standard 類別庫。The dummy project you create to use as startup project provides a concrete target platform into which the tools can load the .NET Standard class library.

ASP.NET Core 環境ASP.NET Core environment

指定 ASP.NET Core 專案的環境,請設定env:ASPNETCORE_ENVIRONMENT之前執行命令。To specify the environment for ASP.NET Core projects, set env:ASPNETCORE_ENVIRONMENT before running commands.

一般參數Common parameters

下表顯示通用於所有的 EF Core 命令的參數:The following table shows parameters that are common to all of the EF Core commands:

參數Parameter 描述Description
內容<字串 >-Context <String> DbContext類別使用。The DbContext class to use. 只有或與命名空間完整限定的類別名稱。Class name only or fully qualified with namespaces. 如果省略這個參數時,EF Core 會尋找內容類別。If this parameter is omitted, EF Core finds the context class. 如果有多個內容類別,這是必要參數。If there are multiple context classes, this parameter is required.
-專案<字串 >-Project <String> 目標專案。The target project. 如果省略這個參數,則預設專案for Package Manager Console做為目標的專案。If this parameter is omitted, the Default project for Package Manager Console is used as the target project.
-啟始專案<字串 >-StartupProject <String> 啟始專案。The startup project. 如果省略這個參數,則啟始專案方案屬性做為目標的專案。If this parameter is omitted, the Startup project in Solution properties is used as the target project.
-Verbose-Verbose 顯示詳細資訊輸出。Show verbose output.

若要顯示命令的說明資訊,請使用 PowerShell 的Get-Help命令。To show help information about a command, use PowerShell's Get-Help command.

提示

內容、 專案和啟始專案參數支援 tab 鍵擴充。The Context, Project, and StartupProject parameters support tab-expansion.

新增移轉Add-Migration

加入新的移轉。Adds a new migration.

參數:Parameters:

參數Parameter 描述Description
-Name<字串 >-Name <String> 移轉名稱。The name of the migration. 這是位置參數,而且為必要。This is a positional parameter and is required.
-OutputDir<字串 >-OutputDir <String> 目錄 (及子命名空間) 使用。The directory (and sub-namespace) to use. 路徑是相對於目標的專案目錄。Paths are relative to the target project directory. 預設為 「 移轉 」。Defaults to "Migrations".

卸除資料庫Drop-Database

卸除資料庫。Drops the database.

參數:Parameters:

參數Parameter 描述Description
-WhatIf-WhatIf 顯示哪個資料庫會卸除,但不會卸除它。Show which database would be dropped, but don't drop it.

Get-DbContextGet-DbContext

列出可用DbContext型別。Lists available DbContext types.

移除移轉Remove-Migration

移除最後一個移轉 (回復移轉已完成的程式碼變更)。Removes the last migration (rolls back the code changes that were done for the migration).

參數:Parameters:

參數Parameter 描述Description
-Force-Force 還原移轉 (回復已套用至資料庫的變更)。Revert the migration (roll back the changes that were applied to the database).

Scaffold DbContextScaffold-DbContext

產生的程式碼DbContext和資料庫的實體類型。Generates code for a DbContext and entity types for a database. 為了讓Scaffold-DbContext來產生實體類型、 資料庫資料表必須有主索引鍵。In order for Scaffold-DbContext to generate an entity type, the database table must have a primary key.

參數:Parameters:

參數Parameter 描述Description
Test-connection<字串 >-Connection <String> 資料庫連接字串。The connection string to the database. 針對 ASP.NET Core 2.x 專案,此值可以是名稱 =<的連接字串名稱 >For ASP.NET Core 2.x projects, the value can be name=<name of connection string>. 在此情況下,名稱來自於 專案設定的組態來源。In that case the name comes from the configuration sources that are set up for the project. 這是位置參數,而且為必要。This is a positional parameter and is required.
提供者<字串 >-Provider <String> 要使用提供者The provider to use. 通常這是 NuGet 套件的名稱,例如: Microsoft.EntityFrameworkCore.SqlServerTypically this is the name of the NuGet package, for example: Microsoft.EntityFrameworkCore.SqlServer. 這是位置參數,而且為必要。This is a positional parameter and is required.
-OutputDir<字串 >-OutputDir <String> 將檔案放入目錄。The directory to put files in. 路徑是相對於專案目錄。Paths are relative to the project directory.
-ContextDir<字串 >-ContextDir <String> 將目錄DbContext檔案中。The directory to put the DbContext file in. 路徑是相對於專案目錄。Paths are relative to the project directory.
內容<字串 >-Context <String> 名稱DbContext類別來產生。The name of the DbContext class to generate.
結構描述<String [] >-Schemas <String[]> 要產生的實體類型的資料表結構描述。The schemas of tables to generate entity types for. 如果省略這個參數,則會包含 所有結構描述。If this parameter is omitted, all schemas are included.
-資料表<String [] >-Tables <String[]> 要產生的實體類型的資料表。The tables to generate entity types for. 如果省略這個參數,則所有資料表都都包含在內。If this parameter is omitted, all tables are included.
-DataAnnotations-DataAnnotations 使用屬性來設定模型 (如果可能的話)。Use attributes to configure the model (where possible). 如果省略這個參數,則會使用 fluent API。If this parameter is omitted, only the fluent API is used.
-UseDatabaseNames-UseDatabaseNames 完全依照其出現在資料庫中,請使用資料表和資料行的名稱。Use table and column names exactly as they appear in the database. 如果省略這個參數,則資料庫名稱會變更為更密切符合 C# 命名樣式慣例。If this parameter is omitted, database names are changed to more closely conform to C# name style conventions.
-Force-Force 覆寫現有的檔案。Overwrite existing files.

範例:Example:

Scaffold-DbContext "Server=(localdb)\mssqllocaldb;Database=Blogging;Trusted_Connection=True;" Microsoft.EntityFrameworkCore.SqlServer -OutputDir Models

範例中,則只有選取的資料表,並建立具有指定名稱的個別資料夾的內容:Example that scaffolds only selected tables and creates the context in a separate folder with a specified name:

Scaffold-DbContext "Server=(localdb)\mssqllocaldb;Database=Blogging;Trusted_Connection=True;" Microsoft.EntityFrameworkCore.SqlServer -OutputDir Models -Tables "Blog","Post" -ContextDir Context -Context BlogContext

Script-MigrationScript-Migration

產生 SQL 指令碼從一個所選移轉至另一個所選的移轉套用的所有變更。Generates a SQL script that applies all of the changes from one selected migration to another selected migration.

參數:Parameters:

參數Parameter 描述Description
-從<字串 >-From <String> 在開始移轉。The starting migration. 移轉可能會識別,依名稱或識別碼。Migrations may be identified by name or by ID. 數字 0 是特殊案例,這表示第一個移轉之前,先The number 0 is a special case that means before the first migration. 預設值為 0。Defaults to 0.
-至<字串 >-To <String> 結束的移轉。The ending migration. 預設為最後一個移轉。Defaults to the last migration.
-具有等冪性-Idempotent 產生可在任何移轉隨時用在資料庫的指令碼。Generate a script that can be used on a database at any migration.
-輸出<字串 >-Output <String> 要將結果寫入其中的檔案。The file to write the result to. 應用程式的執行階段檔案建立時,比方說,如果省略這個參數,則要檔案建立產生的名稱相同的資料夾中: /obj/Debug/netcoreapp2.1/ghbkztfz.sql/IF this parameter is omitted, the file is created with a generated name in the same folder as the app's runtime files are created, for example: /obj/Debug/netcoreapp2.1/ghbkztfz.sql/.

提示

收件者,,和輸出參數支援 tab 鍵擴充。The To, From, and Output parameters support tab-expansion.

下列範例會建立指令碼為 InitialCreate 移轉時,使用移轉名稱。The following example creates a script for the InitialCreate migration, using the migration name.

Script-Migration -To InitialCreate

下列範例會建立所有移轉的指令碼為 InitialCreate 移轉之後,使用 移轉識別碼。The following example creates a script for all migrations after the InitialCreate migration, using the migration ID.

Script-Migration -From 20180904195021_InitialCreate

更新資料庫Update-Database

最後一個移轉,或指定的移轉,請更新資料庫。Updates the database to the last migration or to a specified migration.

參數Parameter 描述Description
-移轉<字串 >-Migration <String> 目標移轉。The target migration. 移轉可能會識別,依名稱或識別碼。Migrations may be identified by name or by ID. 數字 0 是特殊案例,這表示第一個移轉之前,先並造成所有移轉到還原作業。The number 0 is a special case that means before the first migration and causes all migrations to be reverted. 如果未不指定任何移轉,則此命令預設的最後一個移轉。If no migration is specified, the command defaults to the last migration.

提示

移轉參數支援 tab 鍵擴充。The Migration parameter supports tab-expansion.

下列範例會還原所有移轉作業。The following example reverts all migrations.

Update-Database -Migration 0

下列範例會更新資料庫,以指定的移轉。The following examples update the database to a specified migration. 第一個是使用移轉名稱和第二個會使用移轉識別碼:The first uses the migration name and the second uses the migration ID:

Update-Database -Migration InitialCreate
Update-Database -Migration 20180904195021_InitialCreate