我已经搞砸了我的迁移,我在初始迁移上使用了IgnoreChanges,但现在我想删除所有的迁移,并从具有所有逻辑的初始迁移开始。

当我删除文件夹中的迁移并尝试添加- migration时,它不会生成一个完整的文件(它是空的-因为我没有做任何更改,但现在删除了,迁移)。

是否有禁用-迁移命令,以便我可以重新运行启用-迁移?


当前回答

这个方法不需要删除__MigrationHistory表,所以你不必在部署时把你的手放在数据库上。

从migrations文件夹中删除现有的迁移。 在包管理控制台运行Add-Migration ResetMigrations 清理Up()方法中的迁移历史:

/// <summary>
/// Reset existing migrations by cleaning the __MigrationHistory table
/// and creating a new initial migration with the current model snapshot.
/// </summary>
public partial class ResetMigrations : DbMigration
{
    public override void Up()
    {
        Sql("DELETE FROM [dbo].[__MigrationHistory]");
    }

    public override void Down()
    {
    }
}

其他回答

问题:你搞砸了你的迁移,你想重置它而不删除现有的表。

问题:您不能重置数据库中现有表的迁移,因为EF希望从头创建表。

应对方法:

Delete existing migrations from Migrations_History table. Delete existing migrations from the Migrations Folder. Run add-migration Reset. This will create a migration in your Migration folder that includes creating the tables (but it will not run it so it will not error out.) You now need to create the initial row in the MigrationHistory table so EF has a snapshot of the current state. EF will do this if you apply a migration. However, you can't apply the migration that you just made as the tables already exist in your database. So go into the Migration and comment out all the code inside the "Up" method. Now run update-database. It will apply the Migration (while not actually changing the database) and create a snapshot row in MigrationHistory.

现在您已经重置了迁移,可以继续进行正常的迁移。

我的问题是手动删除了Migrations文件夹。我这样做是因为我想备份内容,所以我只是将文件夹拖出项目。后来我修复了这个问题,把它放回去(在做了备份副本之后),然后在解决方案资源管理器中右键单击它并从弹出菜单中选择删除,从而删除了Migrations文件夹。

要解决这个问题,你需要:

删除Migrations文件夹中的所有*.cs文件。 删除数据库中的_MigrationHistory表 执行Enable-Migrations -EnableAutomaticMigrations -Force命令 执行Add-Migration Reset命令

然后,在公共部分类Reset: DbMigration类中,你需要注释所有现有的和当前的table:

public override void Up()
{
// CreateTable(
// "dbo.<EXISTING TABLE NAME IN DATABASE>
// ...
// }
...
}

如果你错过了这一点,一切都将失败,你必须重新开始!

现在运行Update-Database -verbose

如果您正确地完成了上述操作,那么这应该是成功的,现在您可以正常进行了。

如果你知道你的数据库和代码是同步的,现在只是挂在一些简单的事情上,比如试图复制任务的迁移,最简单的方法是重新开始迁移而不丢失数据:

删除VS中的Migrations文件夹。 创建一个新的迁移(例如add-migration InitialCreate) 从__efmigrationhistory db中删除除第一行外的所有内容,并将第一行值更改为带有日期代码的第一个迁移名称(例如20220510060015_InitialCreate)

如果您不知道迁移表的ProductVersion,您可以在新创建的Migrations文件夹中的Designer或Snaphot .cs文件中找到它。

现在,当您运行update-database时,它应该不会出错(并且不执行任何任务)。如果您在早期的迁移中进行了大量的重命名、删除、表、列等操作,那么这可能也是为初始生产环境获得最干净的SQL迁移脚本的好方法。

如果您的代码和db不同步,这取决于您处理的数据量和它们不同步的程度,最好执行上面的步骤1和2,然后备份db并删除它,让迁移从头开始重新创建它,然后恢复数据。

微软:管理迁移-重置所有迁移

To avoid the steps above, sometimes if a migration blows up midway through, you have to step through a migration and comment out each migrationBuilder block that's already completed (in the order they were created), especially if it's not clear from the migration error. So you can look at your db and see that tables, columns, FKs, indexes, etc. that have been dropped, renamed, created, etc. and then just go down the list of migrationBuilder blocks and step through the migration (comment out the completed steps, run update-database again, repeat). When you're done, uncomment everything.

如果表中已经有数据,并且您正在尝试添加FK约束,则可能会遇到另一个常见错误:

无法添加或更新子行:外键约束失败 (Database1。# sql -修改- d9b - 445 b,约束 FK_TableA_TableB_TableBId外键(TableBId)引用 表b (' TableBId)

你要创建FK约束的表,它的FK约束列与主表的PK列不匹配。最好提前做好准备,首先创建一个带有默认值占位符的PK表,但是如果您已经收到了错误,那么我们就在这里。解决这个问题以避免上述一些更激烈的步骤的最简单的方法是:

检查是否创建了FK列,是否分配了默认值(例如,在TableA中,FK约束TableBId = "0")。 修改PK表(或先创建它),使用第一步中分配的默认PK Id记录(例如,在TableB中,创建TableBId = "0"的记录)。 注释掉migrationBuilder之前的所有内容。AddForeignKey块出错并再次运行update-database。迁移现在应该创建FK约束并完成。 取消一切。

对于 EFCore 6/7:

为了将所有更改合并到单个文件中,并将其应用到现有数据库中,同时保留所有数据(即在Production和其他开发中),以下步骤对我来说很有效:

Delete existing migrations from the Migrations Folder in your project. Delete the Context Snapshop files. I.e. ApplicationDbContextSnapshot.cs, DatabaseContextModelSnapshot.cs or similar. Rebuild your solution Run Add-Migration Initial. (Can be named how you like instead of Initial). This will create a migration in your Migration folder that includes creating the tables, but won't be applied yet. Open the generated Migration file and comment out all the code inside the "Up" method, so that it doesn't make any changes to all your existing tables. (This allows us to update the database in the correct format, without making any changes in the next step) Before the commented code within the Up function, add migrationBuilder.Sql("DELETE FROM [dbo].[__EFMigrationsHistory]"); to have the delete/truncate applied during migration

public partial class Initial : Migration
{
    public override void Up()
    {
        migrationBuilder.Sql("DELETE FROM [dbo].[__EFMigrationsHistory]");
        /*
          OTHER COMMENTED OUT CODE
        */
    }

    public override void Down()
    {
    }
}

Run Update-Database. It will apply the Migration and remove existing migration tracking entriers (while not actually changing the database schema) and create a snapshot row in __EFMigrationsHistory Submit this code and apply to your dev, staging and production databases as you normally would (Ensure the code is still commented out in the Up function, no changes will be applied, except a new entry created in __EFMigrationsHistory) Remove migrationBuilder.Sql("DELETE FROM [dbo].[__EFMigrationsHistory]"); and uncomment all the code from step 5 and submit back to source control. (This way new devs can create the db from scratch. If someone forgot to update their existing database, it'll error out and complain that the tables already exist, so they can just comment the Initial file out and apply.)