Entity Framework Core 工具參考.NET CLIEntity Framework Core tools reference - .NET CLI

Entity Framework Core 的命令列介面 (CLI) 工具會執行設計階段開發工作。The command-line interface (CLI) 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. 命令是跨平台的延伸模組dotnet命令,也就是組件的.NET Core SDKThe commands are an extension to the cross-platform dotnet command, which is part of the .NET Core SDK. 這些工具會使用.NET Core 專案。These tools work with .NET Core projects.

如果您使用 Visual Studio,我們建議您Package Manager Console 工具改為:If you're using Visual Studio, we recommend the Package Manager Console tools instead:

  • 它們會自動使用目前的專案中選取Package Manager Console而不需要您手動切換目錄。They automatically work with the current project selected in the Package Manager Console without requiring that you manually switch directories.
  • 它們會自動開啟命令完成之後,命令所產生的檔案。They automatically open files generated by a command after the command is completed.

安裝工具Installing the tools

安裝程序需視專案類型和版本而定:The installation procedure depends on project type and version:

  • EF Core 3.xEF Core 3.x
  • ASP.NET Core 2.1 和更新版本ASP.NET Core version 2.1 and later
  • EF Core 2.xEF Core 2.x
  • EF Core 1.xEF Core 1.x

EF Core 3.xEF Core 3.x

  • dotnet ef 必須安裝做為全域或本機的工具。dotnet ef must be installed as a global or local tool. 大部分的開發人員將會安裝dotnet ef做為全域的工具,使用下列命令:Most developers will install dotnet ef as a global tool with the following command:

      $ dotnet tool install --global dotnet-ef --version 3.0.0-*

    您也可以使用dotnet ef為本機的工具。You can also use dotnet ef as local tool. 若要使用它做為本機的工具,還原專案相依性,將其宣告為使用工具相依性工具資訊清單檔To use it as a local tool, restore the dependencies of a project that declares it as a tooling dependency using a tool manifest file.

  • 安裝.NET Core SDK 3.0)。Install the .NET Core SDK 3.0). SDK 有即使您擁有最新版本的 Visual Studio 安裝。The SDK has to be installed even if you have the latest version of Visual Studio.

  • 安裝最新Microsoft.EntityFrameworkCore.Design封裝。Install the latest Microsoft.EntityFrameworkCore.Design package.

    dotnet add package Microsoft.EntityFrameworkCore.Design

ASP.NET Core 2.1 +ASP.NET Core 2.1+

  • 安裝目前.NET Core SDKInstall the current .NET Core SDK. 即便您有最新版本的 Visual Studio 2017 也必須安裝該 SDK。The SDK has to be installed even if you have the latest version of Visual Studio 2017.

    這是因為,只需要針對 ASP.NET Core 2.1 +Microsoft.EntityFrameworkCore.Design套件包含在Microsoft.AspNetCore.App 中繼套件This is all that is needed for ASP.NET Core 2.1+ because the Microsoft.EntityFrameworkCore.Design package is included in the Microsoft.AspNetCore.App metapackage.

EF Core 2.x (非 ASP.NET Core)EF Core 2.x (not ASP.NET Core)

dotnet ef命令會包含在.NET Core SDK,但若要啟用命令,您必須安裝Microsoft.EntityFrameworkCore.Design封裝。The dotnet ef commands are included in the .NET Core SDK, but to enable the commands you have to install the Microsoft.EntityFrameworkCore.Design package.

  • 安裝目前.NET Core SDKInstall the current .NET Core SDK. SDK 有即使您擁有最新版本的 Visual Studio 安裝。The SDK has to be installed even if you have the latest version of Visual Studio.

  • 安裝最新的穩定Microsoft.EntityFrameworkCore.Design封裝。Install the latest stable Microsoft.EntityFrameworkCore.Design package.

    dotnet add package Microsoft.EntityFrameworkCore.Design

EF Core 1.xEF Core 1.x

  • 安裝.NET Core SDK 版本 2.1.200。Install the .NET Core SDK version 2.1.200. 更新的版本不相容的 EF Core 1.0 和 1.1 版的 CLI 工具。Later versions are not compatible with CLI tools for EF Core 1.0 and 1.1.

  • 設定要使用 2.1.200 SDK 版本的應用程式修改其global.json檔案。Configure the application to use the 2.1.200 SDK version by modifying its global.json file. 此檔案通常會包含在方案目錄 (一個以上專案) 中。This file is normally included in the solution directory (one above the project).

  • 編輯專案檔,並新增Microsoft.EntityFrameworkCore.Tools.DotNet做為DotNetCliToolReference項目。Edit the project file and add Microsoft.EntityFrameworkCore.Tools.DotNet as a DotNetCliToolReference item. 指定的最新的 1.x 版本,例如:1.1.6。Specify the latest 1.x version, for example: 1.1.6. 請參閱專案檔範例,本節結尾處。See the project file example at the end of this section.

  • 安裝的最新的 1.x 版本Microsoft.EntityFrameworkCore.Design套件,例如:Install the latest 1.x version of the Microsoft.EntityFrameworkCore.Design package, for example:

    dotnet add package Microsoft.EntityFrameworkCore.Design -v 1.1.6

    加入這兩個套件參考,專案檔看起來像這樣:With both package references added, the project file looks something like this:

    <Project Sdk="Microsoft.NET.Sdk">
        <PackageReference Include="Microsoft.EntityFrameworkCore.Design"
                           PrivateAssets="All" />
         <DotNetCliToolReference Include="Microsoft.EntityFrameworkCore.Tools.DotNet"
                                Version="1.1.6" />

    使用的套件參考PrivateAssets="All"不公開參考此專案的專案。A package reference with PrivateAssets="All" isn't exposed to projects that reference this project. 這項限制是特別適用於通常只能用在開發期間的套件。This restriction is especially useful for packages that are typically only used during development.

確認安裝Verify installation

執行下列命令來確認已正確安裝 EF Core CLI 工具:Run the following commands to verify that EF Core CLI tools are correctly installed:

dotnet restore
dotnet ef

命令的輸出會識別使用中工具的版本:The output from the command identifies the version of the tools in use:

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

Entity Framework Core .NET Command-line Tools 2.1.3-rtm-32065

<Usage documentation follows, not shown.>

使用的工具Using the tools

之前使用的工具,您可能必須建立啟始專案,或將環境設定。Before using the tools, you might have to create a startup project or set the environment.

目標專案和啟始專案Target project 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 project in the current directory 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 project in the current directory 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

CLI 工具適用於.NET Core 專案和.NET Framework 專案。The CLI tools work with .NET Core projects and .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 主控台應用程式專案。In such cases, you can create a .NET Core 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 執行階段。To do that, they need to use the .NET Core 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 專案的環境,請設定ASPNETCORE_ENVIRONMENT執行命令之前的環境變數。To specify the environment for ASP.NET Core projects, set the ASPNETCORE_ENVIRONMENT environment variable before running commands.

常見的選項Common options

選項Option 說明Description
--json 顯示 JSON 輸出。Show JSON output.
-c --context <DBCONTEXT> 要使用的 DbContext 類別。The DbContext class to use. 只有或與命名空間完整限定的類別名稱。Class name only or fully qualified with namespaces. 如果省略這個選項,EF Core 會發現內容類別。If this option is omitted, EF Core will find the context class. 如果有多個內容類別,這個選項是必要的。If there are multiple context classes, this option is required.
-p --project <PROJECT> 目標專案的專案資料夾的相對路徑。Relative path to the project folder of the target project. 預設值為目前的資料夾。Default value is the current folder.
-s --startup-project <PROJECT> 啟始專案的專案資料夾的相對路徑。Relative path to the project folder of the startup project. 預設值為目前的資料夾。Default value is the current folder.
--framework <FRAMEWORK> 目標 Framework Moniker for目標 frameworkThe Target Framework Moniker for the target framework. 專案檔會指定多個目標架構,而且您想要選取其中一個時,會使用它。Use when the project file specifies multiple target frameworks, and you want to select one of them.
--configuration <CONFIGURATION> 組建組態,例如:DebugReleaseThe build configuration, for example: Debug or Release.
--runtime <IDENTIFIER> 若要還原套件的目標執行階段識別項。The identifier of the target runtime to restore packages for. 如需執行階段識別項 (RID) 清單,請參閱 RID 目錄For a list of Runtime Identifiers (RIDs), see the RID catalog.
-h --help 顯示說明資訊。Show help information.
-v --verbose 顯示詳細資訊輸出。Show verbose output.
--no-color 沒有以色彩標示輸出。Don't colorize output.
--prefix-output 輸出層級的前置詞。Prefix output with level.

dotnet ef 資料庫卸除dotnet ef database drop

卸除資料庫。Drops the database.


選項Option 描述Description
-f --force 未確認。Don't confirm.
--dry-run 顯示哪個資料庫會卸除,但不會卸除它。Show which database would be dropped, but don't drop it.

dotnet ef 資料庫更新dotnet ef database update

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


引數Argument 描述Description
<MIGRATION> 目標移轉。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.

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

dotnet ef database update InitialCreate
dotnet ef database update 20180904195021_InitialCreate

dotnet ef dbcontext 資訊dotnet ef dbcontext info

取得有關的資訊DbContext型別。Gets information about a DbContext type.

dotnet ef dbcontext 清單dotnet ef dbcontext list

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

dotnet ef dbcontext scaffolddotnet ef dbcontext scaffold

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


引數Argument 說明Description
<CONNECTION> 資料庫連接字串。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.
<PROVIDER> 要使用提供者The provider to use. 通常這是 NuGet 套件的名稱,例如: Microsoft.EntityFrameworkCore.SqlServerTypically this is the name of the NuGet package, for example: Microsoft.EntityFrameworkCore.SqlServer.


選項Option 說明Description
-d-d --data-annotations 使用屬性來設定模型 (如果可能的話)。Use attributes to configure the model (where possible). 如果省略這個選項,則會使用 fluent API。If this option is omitted, only the fluent API is used.
-c --context <NAME> 名稱DbContext類別來產生。The name of the DbContext class to generate.
--context-dir <PATH> 將目錄DbContext類別檔案中的。The directory to put the DbContext class file in. 路徑是相對於專案目錄。Paths are relative to the project directory. 命名空間被衍生自資料夾名稱。Namespaces are derived from the folder names.
-f --force 覆寫現有的檔案。Overwrite existing files.
-o --output-dir <PATH> 若要將實體類別檔案放在目錄。The directory to put entity class files in. 路徑是相對於專案目錄。Paths are relative to the project directory.
--schema <SCHEMA_NAME>... 要產生的實體類型的資料表結構描述。The schemas of tables to generate entity types for. 若要指定多個結構描述,請重複--schema針對每個。To specify multiple schemas, repeat --schema for each one. 如果省略這個選項,則會包含 所有結構描述。If this option is omitted, all schemas are included.
-t --table <TABLE_NAME>...--table <TABLE_NAME>... 要產生的實體類型的資料表。The tables to generate entity types for. 若要指定多個資料表,請重複-t--table針對每個。To specify multiple tables, repeat -t or --table for each one. 如果省略這個選項,則所有資料表都都包含在內。If this option is omitted, all tables are included.
--use-database-names 完全依照其出現在資料庫中,請使用資料表和資料行的名稱。Use table and column names exactly as they appear in the database. 如果省略這個選項,則資料庫名稱會變更為更密切符合 C# 命名樣式慣例。If this option is omitted, database names are changed to more closely conform to C# name style conventions.

下列範例則所有的結構描述和資料表,並將新的檔案放在模型資料夾。The following example scaffolds all schemas and tables and puts the new files in the Models folder.

dotnet ef dbcontext scaffold "Server=(localdb)\mssqllocaldb;Database=Blogging;Trusted_Connection=True;" Microsoft.EntityFrameworkCore.SqlServer -o Models

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

dotnet ef dbcontext scaffold "Server=(localdb)\mssqllocaldb;Database=Blogging;Trusted_Connection=True;" Microsoft.EntityFrameworkCore.SqlServer -o Models -t Blog -t Post --context-dir Context -c BlogContext

新增 dotnet ef 移轉dotnet ef migrations add

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


引數Argument 描述Description
<NAME> 移轉名稱。The name of the migration.


選項Option 說明Description
-o --output-dir <PATH> 目錄 (及子命名空間) 使用。The directory (and sub-namespace) to use. 路徑是相對於專案目錄。Paths are relative to the project directory. 預設為 「 移轉 」。Defaults to "Migrations".

dotnet ef migrations 清單dotnet ef migrations list

列出可用的移轉。Lists available migrations.

dotnet ef migrations 移除dotnet ef migrations remove

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


選項Option 說明Description
-f --force 還原移轉 (回復已套用至資料庫的變更)。Revert the migration (roll back the changes that were applied to the database).

dotnet ef migrations 指令碼dotnet ef migrations script

產生 SQL 指令碼從移轉。Generates a SQL script from migrations.


引數Argument 描述Description
<FROM> 在開始移轉。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> 結束的移轉。The ending migration. 預設為最後一個移轉。Defaults to the last migration.


選項Option 描述Description
-o --output <FILE> 要寫入的指令碼檔案。The file to write the script to.
-i --idempotent 產生可在任何移轉隨時用在資料庫的指令碼。Generate a script that can be used on a database at any migration.

下列範例會建立為 InitialCreate 移轉指令碼:The following example creates a script for the InitialCreate migration:

dotnet ef migrations script 0 InitialCreate

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

dotnet ef migrations script 20180904195021_InitialCreate

其他資源Additional resources