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 內執行。The 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 套件包含在AspNetCore 應用程式中繼套件中。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套件。Edit your .csproj file and add a line specifying the latest version of the Microsoft.EntityFrameworkCore.Tools package. 例如, .csproj檔案可能包含如下所示的 ItemGroupFor 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-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'. 更新工具以取得最新功能和錯誤修正。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

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

Install-Package Microsoft.EntityFrameworkCore.Tools

在 [套件管理員主控台] 中執行下列命令,以更新工具。Update 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. 根據預設,在 [套件管理員主控台] 中選取的預設專案是目標專案。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.

其他目標 frameworkOther 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 平臺應用程式。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.

為什麼需要虛擬專案?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. 當 EF Core 模型位於以 .NET Core 或 .NET Framework 為目標的專案中時,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. 如果 EF Core 模型位於 .NET Standard 類別庫中,他們就無法這麼做。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_ENVIRONMENTTo 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 <字串 >-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 <字串 >-Project <String> 目標專案。The target project. 如果省略此參數,則會使用 [封裝管理員主控台] 的預設專案做為目標專案。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.

提示

CoNtext、Project 和啟始專案參數支援 tab 鍵展開。The Context, Project, and StartupProject parameters support tab-expansion.

新增-遷移Add-Migration

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

參數:Parameters:

參數Parameter 描述Description
名稱 <字串 >-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.

DbCoNtextGet-DbContext

取得 DbContext 類型的相關資訊。Gets information about a DbContext type.

Remove-MigrationRemove-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
-連接 <字串 >-Connection <String> 資料庫的連接字串。The connection string to the database. 針對 ASP.NET Core 2.x 專案,此值可以是name =<名稱的連接字串 >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 <字串 >-Context <String> 要產生之 DbContext 類別的名稱。The name of the DbContext class to generate.
-架構 <字串 [] >-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

僅 scaffold 選取的資料表,並在具有指定名稱的另一個資料夾中建立內容的範例: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-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/.

提示

To、From 和 Output 參數支援 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

其他資源Additional resources