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

命令列介面 (CLI) 工具 Entity Framework Core 執行設計階段開發工作。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 SDK的一部分。The 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 時,請考慮使用 封裝管理員主控台工具 代替 CLI 工具。When using Visual Studio, consider using the Package Manager Console tools in lieu of the CLI tools. 自動封裝管理員主控台工具:Package Manager Console tools automatically:

  • 適用于 封裝管理員主控台 中選取的目前專案,不需要您手動切換目錄。Works with the current project selected in the Package Manager Console without requiring that you manually switch directories.
  • 在命令完成之後,開啟命令所產生的檔案。Opens files generated by a command after the command is completed.
  • 提供命令、參數、專案名稱、內容類型和遷移名稱的 tab 鍵自動完成。Provides tab completion of commands, parameters, project names, context types, and migration names.

安裝工具Installing the tools

dotnet ef 可以安裝為全域或本機工具。dotnet ef can be installed as either a global or local tool. 大部分的開發人員偏好 dotnet ef 使用下列命令安裝為通用工具:Most developers prefer installing dotnet ef as a global tool using the following command:

dotnet tool install --global dotnet-ef

若要使用它作為本機工具,請使用 工具資訊清單檔,還原將它宣告為工具相依性之專案的相依性。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.

使用下列命令來更新工具工具:Update the tool tool using the following command:

dotnet tool update --global dotnet-ef

在特定專案上使用工具之前,您必須先將 Microsoft.EntityFrameworkCore.Design 套件新增至其中。Before you can use the tools on a specific project, you'll need to add the Microsoft.EntityFrameworkCore.Design package to it.

dotnet add package Microsoft.EntityFrameworkCore.Design

確認安裝Verify installation

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

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.>

更新工具Update the tools

使用 dotnet tool update --global dotnet-ef 將通用工具更新為最新可用版本。Use dotnet tool update --global dotnet-ef to update the global tools to the latest available version. 如果您已在專案中本機安裝工具,請使用 dotnet tool update dotnet-efIf you have the tools installed locally in your project use dotnet tool update dotnet-ef. 附加 --version <VERSION> 至命令以安裝特定版本。Install a specific version by appending --version <VERSION> to your command. 如需詳細資訊,請參閱 dotnet 工具檔的 更新 一節。See the Update section of the dotnet tool documentation for more details.

使用工具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. 您可以使用選項,將不同的專案指定為目標專案 --projectYou 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-projectYou 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

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 平臺應用程式。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.

為什麼需要虛擬專案?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. 當 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 專案 的環境 ,請先設定 ASPNETCORE_ENVIRONMENT 環境變數,然後再執行命令。To specify the environment for ASP.NET Core projects, set the ASPNETCORE_ENVIRONMENT environment variable before running commands.

從 EF Core 5.0 開始,還可以將額外的引數傳遞至 CreateHostBuilder,讓您在命令列上指定環境:Starting in EF Core 5.0, additional arguments can also be passed into Program.CreateHostBuilder allowing you to specify the environment on the command-line:

dotnet ef database update -- --environment Production

提示

--標記會指示 dotnet ef 將後面的所有專案視為引數,而不會嘗試將它們剖析為選項。The -- token directs dotnet ef to treat everything that follows as an argument and not try to parse them as options. 未使用的任何額外引數 dotnet ef 都會轉送至應用程式。Any extra arguments not used by dotnet ef are forwarded to the app.

一般選項Common options

選項Option ShortShort 描述Description
--json 顯示 JSON 輸出。Show JSON output.
--context <DBCONTEXT> -c 要使用的 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.
--project <PROJECT> -p 目標專案之專案資料夾的相對路徑。Relative path to the project folder of the target project. 預設值為目前的資料夾。Default value is the current folder.
--startup-project <PROJECT> -s 啟始專案專案資料夾的相對路徑。Relative path to the project folder of the startup project. 預設值為目前的資料夾。Default value is the current folder.
--framework <FRAMEWORK> 目標 framework目標 framework 標記The Target Framework Moniker for the target framework. 當專案檔指定多個目標 framework,而您想要選取其中一個 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.
--no-build 請勿建立專案。Don't build the project. 要在組建為最新版本時使用。Intended to be used when the build is up-to-date.
--help -h 顯示說明資訊。Show help information.
--verbose -v 顯示詳細資訊輸出。Show verbose output.
--no-color 請勿將輸出著色。Don't colorize output.
--prefix-output 具有層級的前置詞輸出。Prefix output with level.

從 EF Core 5.0 開始,任何額外的引數都會傳遞至應用程式。Starting in EF Core 5.0, any additional arguments are passed to the application.

dotnet ef database drop

刪除資料庫。Deletes the database.

選項:Options:

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

上述的 通用選項 如下所示。The common options are listed above.

dotnet ef database update

將資料庫更新為上次遷移或指定的遷移。Updates the database to the last migration or to a specified migration.

引數:Arguments:

引數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.

選項:Options:

選項Option 描述Description
--connection <CONNECTION> 資料庫的連接字串。The connection string to the database. 預設為或中所指定 AddDbContextOnConfiguringDefaults to the one specified in AddDbContext or OnConfiguring. 在 EF Core 5.0 中新增。Added in EF Core 5.0.

上述的 通用選項 如下所示。The common options are listed above.

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

dotnet ef database update InitialCreate
dotnet ef database update 20180904195021_InitialCreate --connection your_connection_string

dotnet ef dbcontext info

取得型別的相關資訊 DbContextGets information about a DbContext type.

上述的 通用選項 如下所示。The common options are listed above.

dotnet ef dbcontext list

列出可用 DbContext 的類型。Lists available DbContext types.

上述的 通用選項 如下所示。The common options are listed above.

dotnet 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.

引數:Arguments:

引數Argument 描述Description
<CONNECTION> 資料庫的連接字串。The connection string to the database. 針對 ASP.NET Core 2.x 專案,值可以是 名稱 = <name of connection string>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.

選項:Options:

選項Option ShortShort 描述Description
--data-annotations -d 您可以使用屬性來設定模型 (可能的) 。Use attributes to configure the model (where possible). 如果省略此選項,則只會使用流暢的 API。If this option is omitted, only the fluent API is used.
--context <NAME> -c DbContext要產生的類別名稱。The name of the DbContext class to generate.
--context-dir <PATH> 要放置類別檔案的目錄 DbContextThe directory to put the DbContext class file in. 路徑是相對於專案目錄。Paths are relative to the project directory. 命名空間衍生自資料夾名稱。Namespaces are derived from the folder names.
--context-namespace <NAMESPACE> 要用於產生之類別的命名空間 DbContextThe namespace to use for the generated DbContext class. 注意:覆寫 --namespaceNote: overrides --namespace. 在 EF Core 5.0 中新增。Added in EF Core 5.0.
--force -f 覆寫現有檔案。Overwrite existing files.
--output-dir <PATH> -o 要放置實體類別檔案的目錄。The directory to put entity class files in. 路徑是相對於專案目錄。Paths are relative to the project directory.
--namespace <NAMESPACE> -n 要用於所有產生之類別的命名空間。The namespace to use for all generated classes. 預設為從根命名空間和輸出目錄產生。Defaults to generated from the root namespace and the output directory. 在 EF Core 5.0 中新增。Added in EF Core 5.0.
--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.
--table <TABLE_NAME>...--table <TABLE_NAME>... -t 要產生之實體類型的資料表。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.
--no-onconfiguring 隱藏 OnConfiguring 產生的類別中的方法產生 DbContextSuppresses generation of the OnConfiguring method in the generated DbContext class. 在 EF Core 5.0 中新增。Added in EF Core 5.0.
--no-pluralize 請勿使用 pluralizer。Don't use the pluralizer. 新增于 EF Core 5。0Added in EF Core 5.0

上述的 通用選項 如下所示。The common options are listed above.

下列範例會 scaffold 所有架構和資料表,並將新檔案放在 [ 模型 ] 資料夾中。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

下列範例只會 scaffold 選取的資料表,並在具有指定之名稱和命名空間的個別資料夾中建立內容:The following example scaffolds only selected tables and creates the context in a separate folder with a specified name and namespace:

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 --context-namespace New.Namespace

下列範例會使用 Secret Manager 工具,從專案的設定集讀取連接字串。The following example reads the connection string from the project's configuration set using the Secret Manager tool.

dotnet user-secrets set ConnectionStrings:Blogging "Data Source=(localdb)\MSSQLLocalDB;Initial Catalog=Blogging"
dotnet ef dbcontext scaffold Name=ConnectionStrings:Blogging Microsoft.EntityFrameworkCore.SqlServer

dotnet ef dbcontext script

從 DbCoNtext 產生 SQL 腳本。Generates a SQL script from the DbContext. 略過任何遷移。Bypasses any migrations. 在 EF Core 3.0 中新增。Added in EF Core 3.0.

選項:Options:

選項Option ShortShort 描述Description
--output <FILE> -o 要寫入結果的檔案。The file to write the result to.

上述的 通用選項 如下所示。The common options are listed above.

dotnet ef migrations add

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

引數:Arguments:

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

選項:Options:

選項Option ShortShort 描述Description
--output-dir <PATH> -o 用來輸出檔案的目錄。The directory use to output the files. 路徑是相對於目標專案目錄。Paths are relative to the target project directory. 預設為「遷移」。Defaults to "Migrations".
--namespace <NAMESPACE> -n 要用於產生之類別的命名空間。The namespace to use for the generated classes. 預設為從輸出目錄產生。Defaults to generated from the output directory. 在 EF Core 5.0 中新增。Added in EF Core 5.0.

上述的 通用選項 如下所示。The common options are listed above.

dotnet ef migrations list

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

選項:Options:

選項Option 描述Description
--connection <CONNECTION> 資料庫的連接字串。The connection string to the database. 預設為 AddDbCoNtext 或 OnConfiguring 中指定的值。Defaults to the one specified in AddDbContext or OnConfiguring. 在 EF Core 5.0 中新增。Added in EF Core 5.0.
--no-connect 請勿連接至資料庫。Don't connect to the database. 在 EF Core 5.0 中新增。Added in EF Core 5.0.

上述的 通用選項 如下所示。The common options are listed above.

dotnet ef migrations remove

移除最後一個遷移 (復原針對遷移) 所做的程式碼變更。Removes the last migration (rolls back the code changes that were done for the migration).

選項:Options:

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

上述的 通用選項 如下所示。The common options are listed above.

dotnet ef migrations script

從遷移產生 SQL 腳本。Generates a SQL script from migrations.

引數:Arguments:

引數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.

選項:Options:

選項Option ShortShort 描述Description
--output <FILE> -o 要寫入腳本的檔案。The file to write the script to.
--idempotent -i 產生可在任何遷移時用於資料庫的腳本。Generate a script that can be used on a database at any migration.
--no-transactions 不要產生 SQL 交易語句。Don't generate SQL transaction statements. 在 EF Core 5.0 中新增。Added in EF Core 5.0.

上述的 通用選項 如下所示。The common options are listed above.

下列範例會建立 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