你的位置:首页 > ASP.net教程

[ASP.net教程]EF架构~CodeFirst生产环境的Migrations

回到目录

Migrations即迁移,它是EF的code first模式出现的产物,它意思是说,将代码的变化反映到数据库上,这种反映有两种环境,一是本地开发环境,别一种是服务器的生产环境,本地开发环境主要使用包管理工具的update-database即可完成数据库的迁移(变更),而在生产环境就显得麻烦一些,因为你不会在生产环境放程序源代码和VS开发工具,哈哈.

本地数据库迁移请看我的这篇文章

EF架构~CodeFirst数据迁移与防数据库删除

服务器上生产环境的数据迁移

如果我们有迁移文件如下

public partial class manager : DbMigration  {    public override void Up()    {      DropForeignKey("dbo.WebDataSettings", "WebDataCtrlId", "dbo.WebDataCtrls");      DropForeignKey("dbo.WebDataSettings", "DepartmentId", "dbo.WebDepartments");      RenameColumn(table: "dbo.WebDataSettings", name: "DepartmentId", newName: "WebDepartmentsId");      RenameIndex(table: "dbo.WebDataSettings", name: "IX_DepartmentId", newName: "IX_WebDepartmentsId");      AddForeignKey("dbo.WebDataSettings", "WebDataCtrlId", "dbo.WebDataCtrls", "ID", cascadeDelete: true);      AddForeignKey("dbo.WebDataSettings", "WebDepartmentsId", "dbo.WebDepartments", "ID", cascadeDelete: true);    }        public override void Down()    {      DropForeignKey("dbo.WebDataSettings", "WebDepartmentsId", "dbo.WebDepartments");      DropForeignKey("dbo.WebDataSettings", "WebDataCtrlId", "dbo.WebDataCtrls");      RenameIndex(table: "dbo.WebDataSettings", name: "IX_WebDepartmentsId", newName: "IX_DepartmentId");      RenameColumn(table: "dbo.WebDataSettings", name: "WebDepartmentsId", newName: "DepartmentId");      AddForeignKey("dbo.WebDataSettings", "DepartmentId", "dbo.WebDepartments", "ID");      AddForeignKey("dbo.WebDataSettings", "WebDataCtrlId", "dbo.WebDataCtrls", "ID");    }  }

在本地VS中执行下面命令,它将生产迁移计划,即SQL语句

Update-Database -Script -SourceMigration: $InitialDatabase -TargetMigration:manage

它将生成对应的SQL脚本,我们在服务器上运行即可

幂等性

由Migration生成的SQL脚本是幂等的,即,当你多次执行SQL脚本时,产生的结果是一样的,不对有负作用.

回到目录