Code First 数据迁移

迁移”是一组有序的步骤,描述如何升级(和降级)数据库架构。

 

当模型发生变化时

1、“工具”->“NuGet包管理器”->“程序包管理器控制台”
在程序包管理器控制台中运行 Enable-Migrations 命令

PM> Enable-Migrations
Checking if the context targets an existing database...
PM>

生成一个 Migrations 文件夹,它包含1个文件:Configuration.cs 

 

2、在程序包管理器控制台中运行 Add-Migration XX 命令。

XX 是名称,例如dd

PM> Add-Migration dd
Scaffolding migration 'dd'.
The Designer Code for this migration file includes a snapshot of your current Code First model. This snapshot is used to calculate the changes to your model when you scaffold the next migration. If you make additional changes to your model that you want to include in this migration, then you can re-scaffold it by running 'Add-Migration dd' again.
PM>

在文件夹 Migrations 中生成 文件:202108071428537_dd.cs ,前面是时间

 

3、在程序包管理器控制台中运行 Update-Database 命令。此命令将所有挂起的迁移应用于数据库。

PM> Update-Database
Specify the '-Verbose' flag to view the SQL statements being applied to the target database.
Applying explicit migrations: [202108071428537_dd].
Applying explicit migration: 202108071428537_dd.
Running Seed method.
PM>

  

 添加新模型,例如UserAA

1、定义UserAA模型类;

2、在DbContext 上下文中定义 public DbSet<UserAA> UserAA { get; set; }

3、按照上面的步骤迁移

 

删除1个模型,例如UserAA

1、删除UserAA模型类;

2、在DbContext 上下文中删除 public DbSet<UserAA> UserAA { get; set; }

3、按照上面的步骤迁移

 

posted @ 2021-08-07 22:34  清语堂  阅读(125)  评论(0编辑  收藏  举报