EF Migrations Command Reference (EF 迁移命令)

本文详细介绍了 Entity Framework Migrations 在 Visual Studio 的包管理控制台中的使用方法,包括启用迁移、添加迁移、更新数据库和获取已应用迁移等命令的详细说明及参数解析。

Entity Framework Migrations are handled from the package manager console in Visual Studio. The usage is shown in various tutorials, but I haven’t found a complete list of the commands available and their usage, so I created my own. There are four available commands.

 

The information here is the output of running get-help command-name -detailed for each of the commands in the package manager console (running EF 4.3.1). I’ve also added some own comments where I think some information is missing. My own comments are placed under the Additional Information heading.

Please note that all commands should be entered on the same line. I’ve added line breaks to avoid vertical scrollbars.

Enable-Migrations

Enables Code First Migrations in a project.

Syntax

Enable-Migrations [-EnableAutomaticMigrations] [[-ProjectName] <String>]
  [-Force] [<CommonParameters>]

Description

Enables Migrations by scaffolding a migrations configuration class in the project. If the  target database was created by an initializer, an initial migration will be created (unless automatic migrations are enabled via the EnableAutomaticMigrations parameter).

Parameters

-EnableAutomaticMigrations

Specifies whether automatic migrations will be enabled in the scaffolded migrations configuration. If ommitted, automatic migrations will be disabled.

-ProjectName <String>

Specifies the project that the scaffolded migrations configuration class will be added to. If omitted, the default project selected in package manager console is used.

-Force

Specifies that the migrations configuration be overwritten when running more than once for given project.

<CommonParameters>

This cmdlet supports the common parameters: Verbose, Debug, ErrorAction, ErrorVariable, WarningAction, WarningVariable, OutBuffer and OutVariable. For more information, type: get-help about_commonparameters.

Remarks

To see the examples, type: get-help Enable-Migrations -examples.
For more information, type: get-help Enable-Migrations -detailed.
For technical information, type: get-help Enable-Migrations -full.

Additional Information

The flag for enabling automatic migrations is saved in the Migrations\Configuration.cs file, in the constructor. To later change the option, just change the assignment in the file.

public Configuration()
{
    AutomaticMigrationsEnabled = false;
}

Add-Migration

Scaffolds a migration script for any pending model changes.

Syntax

Add-Migration [-Name] <String> [-Force]
  [-ProjectName <String>] [-StartUpProjectName <String>]
  [-ConfigurationTypeName <String>] [-ConnectionStringName <String>]
  [-IgnoreChanges] [<CommonParameters>]
 
Add-Migration [-Name] <String> [-Force]
  [-ProjectName <String>] [-StartUpProjectName <String>]
  [-ConfigurationTypeName <String>] -ConnectionString <String>
  -ConnectionProviderName <String> [-IgnoreChanges] [<Common Parameters>]

Description

Scaffolds a new migration script and adds it to the project.

Parameters

-Name <String>

Specifies the name of the custom script.

-Force

Specifies that the migration user code be overwritten when re-scaffolding an existing migration.

-ProjectName <String>

Specifies the project that contains the migration configuration type to be used. If ommitted, the default project selected in package manager console is used.

-StartUpProjectName <String>

Specifies the configuration file to use for named connection strings. If omitted, the specified project’s configuration file is used.

-ConfigurationTypeName <String>

Specifies the migrations configuration to use. If omitted, migrations will attempt to locate a single migrations configuration type in the target project.

-ConnectionStringName <String>

Specifies the name of a connection string to use from the application’s configuration file.

-ConnectionString <String>

Specifies the the connection string to use. If omitted, the context’s default connection will be used.

-ConnectionProviderName <String>

Specifies the provider invariant name of the connection string.

-IgnoreChanges

Scaffolds an empty migration ignoring any pending changes detected in the current model. This can be used to create an initial, empty migration to enable Migrations for an existing database. N.B. Doing this assumes that the target database schema is compatible with the current model.

<CommonParameters>

This cmdlet supports the common parameters: Verbose, Debug, ErrorAction, ErrorVariable, WarningAction, WarningVariable, OutBuffer and OutVariable. For more information, type: get-help about_commonparameters.

Remarks

To see the examples, type: get-help Add-Migration -examples.
For more information, type: get-help Add-Migration -detailed.
For technical information, type: get-help Add-Migration -full.

Update-Database

Applies any pending migrations to the database.

Syntax

Update-Database [-SourceMigration <String>]
  [-TargetMigration <String>] [-Script] [-Force] [-ProjectName <String>]
  [-StartUpProjectName <String>] [-ConfigurationTypeName <String>]
  [-ConnectionStringName <String>] [<CommonParameters>]
 
Update-Database [-SourceMigration <String>] [-TargetMigration <String>]
  [-Script] [-Force] [-ProjectName <String>] [-StartUpProjectName <String>]
  [-ConfigurationTypeName <String>] -ConnectionString <String>
  -ConnectionProviderName <String> [<CommonParameters>]

Description

Updates the database to the current model by applying pending migrations.

Parameters

-SourceMigration <String>

Only valid with -Script. Specifies the name of a particular migration to use as the update’s starting point. If ommitted, the last applied migration in the database will be used.

-TargetMigration <String>

Specifies the name of a particular migration to update the database to. If ommitted, the current model will be used.

-Script

Generate a SQL script rather than executing the pending changes directly.

-Force

Specifies that data loss is acceptable during automatic migration of the
database.

-ProjectName <String>

Specifies the project that contains the migration configuration type to be used. If ommitted, the default project selected in package manager console is used.

-StartUpProjectName <String>

Specifies the configuration file to use for named connection strings. If omitted, the specified project’s configuration file is used.

-ConfigurationTypeName <String>

Specifies the migrations configuration to use. If omitted, migrations will attempt to locate a single migrations configuration type in the target project.

-ConnectionStringName <String>

Specifies the name of a connection string to use from the application’s configuration file.

-ConnectionString <String>

Specifies the the connection string to use. If omitted, the context’s default connection will be used.

-ConnectionProviderName <String>

Specifies the provider invariant name of the connection string.

<CommonParameters>

This cmdlet supports the common parameters: Verbose, Debug, ErrorAction, ErrorVariable, WarningAction, WarningVariable, OutBuffer and OutVariable. For more information, type: get-help about_commonparameters.

Remarks

To see the examples, type: get-help Update-Database -examples.
For more information, type: get-help Update-Database -detailed.
For technical information, type: get-help Update-Database -full.

Additional Information

The command always runs any pending code-based migrations first. If the database is still incompatible with the model the additional changes required are applied as an separate automatic migration step if automatic migrations are enabled. If automatic migrations are disabled an error message is shown.

Get-Migrations

Displays the migrations that have been applied to the target database.

Syntax

Get-Migrations [-ProjectName <String>] [-StartUpProjectName <String>]
  [-ConfigurationTypeName <String>] [-ConnectionStringName <String>]
  [<CommonParameters>]
 
Get-Migrations [-ProjectName <String>] [-StartUpProjectName <String>]
  [-ConfigurationTypeName <String>] -ConnectionString <String>
  -ConnectionProviderName <String> [<CommonParameters>]

Description

Displays the migrations that have been applied to the target database.

Parameters

-ProjectName <String>

Specifies the project that contains the migration configuration type to be used. If ommitted, the default project selected in package manager console is used.

-StartUpProjectName <String>

Specifies the configuration file to use for named connection strings. If omitted, the specified project’s configuration file is used.

-ConfigurationTypeName <String>

Specifies the migrations configuration to use. If omitted, migrations will attempt to locate a single migrations configuration type in the target project.

-ConnectionStringName <String>

Specifies the name of a connection string to use from the application’s configuration file.

-ConnectionString <String>

Specifies the the connection string to use. If omitted, the context’s default connection will be used.

-ConnectionProviderName <String>

Specifies the provider invariant name of the connection string.

<CommonParameters>

This cmdlet supports the common parameters: Verbose, Debug, ErrorAction, ErrorVariable, WarningAction, WarningVariable, OutBuffer and OutVariable. For more information, type: get-help about_commonparameters.

Remarks

To see the examples, type: get-help Get-Migrations -examples.
For more information, type: get-help Get-Migrations -detailed.
For technical information, type: get-help Get-Migrations -full.

Additional Information

The powershell commands are complex powershell functions, located in the tools\EntityFramework.psm1 file of the Entity Framework installation. The powershell code is mostly a wrapper around the System.Data.Entity.Migrations.MigrationsCommands found in the tools\EntityFramework\EntityFramework.PowerShell.dll file. First a MigrationsCommands object is instantiated with all configuration parameters. Then there is a public method on the MigrationsCommands object for each of the available commands.
YJY5P7USBQX

<think>我们正在寻找Entity Framework Core的迁移命令列表。这些命令用于管理数据库迁移,包括创建迁移、应用迁移、回滚迁移等。 根据用户提供的引用,他们似乎在使用Entity Framework Core(在C#中)和Spring Security(在Java中),但主要问题集中在EF Core迁移命令上。 因此,我们将提供Entity Framework Core的迁移相关命令。 注意:这些命令是通过.NET Core CLI(命令行界面)或Package Manager Console(在Visual Studio中)执行的。 主要命令如下: 1. 创建迁移(Add-Migration): 用于基于模型的更改创建新的迁移文件。 2. 更新数据库(Update-Database): 将挂起的迁移应用到数据库。 3. 移除迁移(Remove-Migration): 移除最后一次创建的迁移(如果尚未应用到数据库)。 4. 生成SQL脚本(Script-Migration): 生成一个SQL脚本,用于将数据库从当前状态迁移到目标迁移状态。 5. 列出迁移(Get-Migrations): 列出已应用到数据库的所有迁移。 6. 数据库相关命令(DbContext): 用于DbContext相关的操作,例如检查数据库状态。 下面我们将详细列出这些命令及其常用参数。 注意:有两种执行环境: - Package Manager Console(在Visual Studio中):使用类似PowerShell的命令(例如:Add-Migration)。 - .NET Core CLI(命令行):使用dotnet ef命令(例如:dotnet ef migrations add)。 我们将分别列出这两种环境下的命令。</think>以下是 Entity Framework Core 的核心迁移命令列表,用于数据库模式管理和版本控制: ### 一、核心迁移命令(通过 .NET CLI) | 命令 | 说明 | 示例 | |------|------|------| | `dotnet ef migrations add` | 创建新迁移文件 | `dotnet ef migrations add InitialCreate` | | `dotnet ef migrations remove` | 删除最新迁移文件 | `dotnet ef migrations remove` | | `dotnet ef migrations list` | 列出所有迁移 | `dotnet ef migrations list` | | `dotnet ef database update` | 应用挂起迁移数据库 | `dotnet ef database update` | | `dotnet ef database update --target` | 迁移到特定版本 | `dotnet ef database update 202405121234_InitialCreate` | | `dotnet ef migrations script` | 生成迁移SQL脚本 | `dotnet ef migrations script -o migration.sql` | | `dotnet ef database drop` | 删除数据库 | `dotnet ef database drop --force` | ### 二、Visual Studio 包管理器控制台命令 | 命令 | 等价命令 | |------|----------| | `Add-Migration` | `dotnet ef migrations add` | | `Remove-Migration` | `dotnet ef migrations remove` | | `Update-Database` | `dotnet ef database update` | | `Script-Migration` | `dotnet ef migrations script` | ### 三、关键工作流示例 1. **创建并应用迁移** ```bash dotnet ef migrations add AddProductTable dotnet ef database update ``` 2. **生成回滚脚本** ```bash # 生成从当前版本回退到初始状态的SQL dotnet ef migrations script InitialCreate AddProductTable -o rollback.sql ``` 3. **迁移到特定版本** ```bash dotnet ef database update 202405120800_InitialCreate ``` ### 四、高级配置 1. **在代码中执行迁移**(如引用[3]所示) ```csharp // Startup.cs public void Configure(IApplicationBuilder app, BloggingContext context) { context.Database.Migrate(); // 自动应用挂起迁移 } ``` 2. **在DbContext中检查迁移**(如引用[1]所示) ```csharp public class DataContext : DbContext { public DataContext(DbContextOptions<DataContext> options) : base(options) { if (Database.GetPendingMigrations().Any()) { Database.Migrate(); // 执行迁移 } } } ``` ### 五、最佳实践 1. **迁移文件管理** - 每个迁移应有描述性名称(如 `AddUserEmailColumn`) - 避免直接修改已提交的迁移文件 - 团队共享时需同步迁移文件 2. **生产环境部署** - 使用 `dotnet ef migrations script` 生成SQL脚本审核后再执行 - 结合CI/CD管道自动化迁移流程 - 始终在部署前备份数据库 > **迁移原理**:EF Core通过 `__EFMigrationsHistory` 表跟踪已应用的迁移[^1],迁移文件包含 `Up()` 和 `Down()` 方法分别对应应用和回滚操作。 ---
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值