ef数据迁移命令总结之Add-Migration

本文介绍了Entity Framework的Add-Migration命令,用于将模型更改转化为数据库迁移脚本。命令用于创建新的迁移,其中Name参数指定脚本名称,-Force参数允许重写已存在迁移的代码。此外,还涉及了项目和配置文件的选择,以及如何处理多个DbContext的情况。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

ef数据迁移命令总结之Add-Migration

首先我们可以在vs的程序包管理控制台输入 get-help Add-Migration -detailed以查看详细信息。

个人感觉有一篇好的文章,http://www.mortenanderson.net/code-first-migrations-for-entity-framework ,
在本人的感觉就是 其对这些命令的掌握很深刻,所以在项目中摘录好的地方进行翻译,如果侵权,请联系删除。


Add-Migration 
-Name LearningMpaAbp.EntityFramework 
-Force 
-ProjectName LearningMpaAbp.EntityFramework  
-StartUpProjectName ConsoleApp1  
-ConfigurationTypeName  LearningMpaAbp.Migrations.Configuration 
-ConnectionStringName Default  


Add-Migration 
-Name LearningMpaAbp.EntityFramework 
-Force 
-ProjectName LearningMpaAbp.EntityFramework  
-StartUpProjectName ConsoleApp1  
-ConfigurationTypeName  LearningMpaAbp.Migrations.Configuration 
<!-- 如下和上边的 -ConnectionStringName Default  的作用是一样的 -->
-ConnectionString "data source=DESKTOP-H6LD3FA\SQLEXPRESS;Database=LearningMpaAbp;User Id=sa;Password=123456;" 
-ConnectionProviderName System.Data.SqlClient



名称Add-Migration

The add-migration command is one of the key commands in code first migrations. When you make changes to your domain model and need them dded into your database you create a new migration. This is done with the Add-Migration command. In it’s simplest form you need only toprovide a migration name.

add-migration命令是code first migration中的关键命令之一。当您对领域域模型进行更改并需要将它们时添加到数据库中,您将创建一个新的迁移。这是通过Add-Migration命令完成的。用最简单的形式,你只需要提供迁移名称。

The Add-Migration command scaffolds your changes into a cs file. This cs file is placed in the same folder as the configuration file for the DbContext you are targeting.

Add-Migration命令将您的更改构建到一个cs文件中。这个cs文件与配置文件放在同一个文件夹中,服务于您要瞄准的DbContext。

摘要
Scaffolds a migration script for any pending model changes.
为任何待定的模型更改 搭建迁移脚本。

语法

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

说明
Scaffolds a new migration script and adds it to the project.
搭建一个新的数据迁移脚本 ,并把它添加到项目中。

参数
-Name

Specifies the name of the custom script.

指定自定义脚本 的名字

-Force []

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

指定 当我们重新 搭建一个已经存在的数据迁移的时候,原本存在的数据迁移代码可以被重写

If you want to re-scaffold an existing migration you will have to use the -Force parameter. However you can only re-scaffold if the migration is not yet applied to database. Else you will need to revert back to the migration previous to the one you want to re-scaffold.

如果要重新构建现有迁移,必须使用-Force参数。然而,只有在迁移尚未应用到数据库时,才能重新构建框架。否则你 需要回复到要重新构建的迁移之前的迁移。

-ProjectName

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

指定 包含了数据迁移配置类型的项目,如果被忽略,就会选择包管理控制器中的默认项目。

If your migrations should not be placed in your default project you can utilize the -projectname parameter

-StartUpProjectName

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

这个其实我也看不懂, 但实验之后,大概是从 解决方案资源管理器中选择一个项目 作为启动项目。如果我们忽略的话,就会默认为解决方案资源管理器中的启动项目。

-ConfigurationTypeName

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

这一段英文解释了,大概还是不会懂。

If you have multiple DbContext in your project you will need to indicate which is going to have the database update. This can be done with -ConfigurationTypeName. The ConfigurationTypeName is the name of your Configuration class in your migration folder.

如果您的项目中有多个DbContext,那么您需要指出哪个数据库会更新。这可以用-ConfigurationTypeName做。ConfigurationTypeName方法是迁移文件夹中配置类的名称。

然后是一个多个DbContext的例子
		
  First step
  ==========
  
  enable-migrations -ContextTypeName IdentityDb -MigrationsDirectory DAL\IdentityMigrations
  
  enable-migrations -ContextTypeName SMSContext -MigrationsDirectory DAL\SMSMigrations
  
  Second Step
  ===========
  
  add-migration -ConfigurationTypeName SMSApp.DAL.IdentityMigrations.Configuration "InitialCreate"
  
  add-migration -ConfigurationTypeName SMSApp.DAL.SMSMigrations.Configuration "InitialCreate"
  
  Third Step
  ==========
  
  update-database -ConfigurationTypeName SMSApp.DAL.IdentityMigrations.Configuration -verbose
  
  update-database -ConfigurationTypeName SMSApp.DAL.SMSMigrations.Configuration -verbose

-ConnectionStringName

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

从应用程序的配置文件中指定要使用的连接字符串的名字。我们用两个参数-ConnectionString -ConnectionProviderName ,或者用这样一个参数代替

-ConnectionString

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

指定要使用的连接字符串。如果省略,上将使用DbContext的默认连接。
例如"data source=DESKTOP-H6LD3FA\SQLEXPRESS;Database=LearningMpaAbp;User Id=sa;Password=123456;"

-ConnectionProviderName

指定ConnectionProviderName 例如 System.Data.SqlClient

-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.
这样做假设目标数据库模式与当前的模型是一致的。构建一个空迁移和对应的空的迁移文件,忽略在当前模型中检测到的任何挂起的更改。可用于创建初始的空迁移,以支持对现有数据库的迁移。

-AppDomainBaseDirectory

Specifies the directory to use for the app-domain that is used for running Migrations code such that the app-domain is able to find all required assemblies. This is an advanced option that should only be needed if the solution contains several projects such that the assemblies needed for the context and configuration are not all referenced from either the project containing the context or the project containing the migrations.
指定用于运行数据迁移代码的app-domain的路径,从而app-domain 可以找到所有需要的程序集。这是一个高级选项,只有当解决方案包含多个项目时才会需要。这样的话,context和configuration所需要的程序集就不仅仅从那些包含context和包含migrations的项目中获取。

<think>嗯,用户遇到了在使用Add-Migration命令时因为项目构建失败导致迁移无法执行的问题。我需要根据提供的引用和之前的知识来找出解决方案。首先,引用[1]提到如果项目有语法错误,迁移工具会提示“Build failed”,所以首先应该检查代码中的语法错误。用户可能需要先修复这些错误才能继续。 然后,引用[2]指出目标项目与迁移程序集不匹配的问题。这通常发生在DbContext所在的程序集和迁移命令执行的项目不一致时。用户可能需要确认他们是否正确设置了默认项目或者在DbContext配置中指定了迁移程序集。例如,在UseSqlServer方法里使用MigrationsAssembly参数来指定正确的程序集。 另外,引用[3]是关于EF Core与MySQL迁移失败的配置问题。用户需要检查项目文件(比如.csproj)是否正确引用了必要的包,如Pomelo.EntityFrameworkCore.MySql和Microsoft.EntityFrameworkCore.Tools,并且版本是否兼容。有时候包版本不匹配会导致构建失败。 可能还需要检查项目是否能够成功手动构建,如果命令行工具无法构建,手动构建可能会暴露更多细节的错误信息。此外,清理解决方案和重新生成项目有时可以解决临时构建问题。 总结下来,解决方案应该分步骤:首先修复代码错误,然后检查项目配置和依赖项,接着确认迁移程序集的设置是否正确,最后确保所有工具和包版本兼容。同时,提醒用户避免手动修改EFMigrationsHistory表,以免引发其他问题。</think>### 逐步解决方案:数据库迁移 Add-Migration 构建失败 #### 1. **检查项目构建错误** - **核心原因**:`Add-Migration` 命令执行前会尝试构建项目,若存在代码语法错误、缺少依赖项或命名空间冲突,会导致构建失败。 - **操作步骤**: 1. 在Visual Studio中手动构建项目(快捷键 `Ctrl+Shift+B`),观察输出窗口中的具体错误。 2. 修复所有编译错误,例如: - 缺少分号、括号不匹配 - 未引用的命名空间(如 `using Microsoft.EntityFrameworkCore;`) - 未实现的接口或抽象方法 - **示例**:若输出提示 `CS1002: 应输入 ;`,需检查对应代码行的语法完整性。 #### 2. **验证迁移程序集配置** - **核心原因**:DbContext 所在程序集与迁移命令执行的目标项目不一致[^2]。 - **操作步骤**: 1. **方法一**:在包管理器控制台(PMC)中,通过 **“默认项目”下拉框** 选择包含 `DbContext` 的项目。 2. **方法二**:在 `DbContext` 配置中显式指定迁移程序集: ```csharp protected override void OnConfiguring(DbContextOptionsBuilder options) { options.UseSqlServer(connectionString, b => b.MigrationsAssembly("目标项目名称")); } ``` #### 3. **检查NuGet包兼容性** - **核心原因**:EF Core工具包(如 `Microsoft.EntityFrameworkCore.Tools`)与数据库驱动(如 `Pomelo.EntityFrameworkCore.MySql`)版本不兼容[^3]。 - **操作步骤**: 1. 打开项目文件(`.csproj`),检查以下包版本是否一致: ```xml <PackageReference Include="Microsoft.EntityFrameworkCore" Version="x.x.x" /> <PackageReference Include="Microsoft.EntityFrameworkCore.Tools" Version="x.x.x"> <PrivateAssets>all</PrivateAssets> </PackageReference> <PackageReference Include="Pomelo.EntityFrameworkCore.MySql" Version="x.x.x" /> ``` 2. 使用NuGet包管理器更新所有EF Core相关包至兼容版本。 #### 4. **清理并重建项目** - **操作步骤**: 1. 执行 `dotnet clean` 或通过Visual Studio菜单 **“生成” → “清理解决方案”**。 2. 重新生成项目(`dotnet build` 或 `Ctrl+Shift+B`)。 #### 5. **手动触发迁移命令** - 若仍失败,尝试通过命令行执行(需安装.NET Core CLI工具): ```bash dotnet ef migrations add InitialCreate --project 目标项目路径 --startup-project 启动项目路径 ``` --- ### 常见错误与解决方案 | 错误类型 | 示例 | 解决方案 | |---------|------|----------| | 语法错误 | `CS1002: 应输入 ;` | 检查代码行结尾符号 | | 程序集不匹配 | `Your target project 'A' doesn't match migrations assembly 'B'` | 配置 `MigrationsAssembly` 或切换PMC默认项目[^2] | | 包版本冲突 | `No overload for method 'UseMySql' takes 1 arguments` | 升级 `Pomelo.EntityFrameworkCore.MySql` 至兼容版本 | ---
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值