ef-->code first-->Migrations

来源:互联网 发布:java登陆注册实现 编辑:程序博客网 时间:2024/05/16 17:59

1.Tools –> Library Package Manager –> Package Manager Console


2.Run the ‘Install-Package EntityFramework’ command


3.添加继承DbContext的上下文(比如:TestDbContext)。
public class TestDbContext:DbContext{
    ......
}


4.Run the ‘Enable-Migrations’ command in Package Manager Console
  上面的命令执行之后,在你的项目里就会新建一个文件加,文件夹里有两个文件,分别是Configuration 和InitialCreate migration


5.接下来我们就可以使用EF的Migration来为某个类对象添加新的属性并同步到数据库,比如:AddTestUrl类;
  Run the ‘Add-Migration AddTestUrl’ command in Package Manager Console,之后项目的文件夹下就会新建一个AddTestUrl migration文件里面主要包括两个函数,其中up用于数据迁移,down用于数据回溯,当然如果觉得这些操作还不够可以自己手动修改里面的操作.


6.Run the ‘Update-Database’ command in Package Manager Console,这样我们对model的修改就会更新到数据库里


7.添加完字段之后,我们发现还是原来的设计更好,这时我们就需要回溯我们的数据库:Run the ‘Update-Database –TargetMigration:"InitialCreate"’ command in Package Manager Console.,此时数据库就又回到了刚开始建的是时候,
查看sql:我们在 Package Manager Console执行相关的命令之后,数据库就做出来相应的改变,如果我们想查看数据迁移过程中这些命令到底为我们做了什么,我们可以使用-script来获取各个migration的sql,比如我们migrations文件夹下只有两个migration。


8.我们想查看InitialCreate具体执行了哪些脚本:
  我们可以Run the ‘Update-Database –TargetMigration:"InitialCreate"’ command in Package Manager Console,
  查看AddBlogUrl具体执行了哪些脚本,我们可以Run the ‘Update-Database –TargetMigration:"AddBlogUrl"’ command in Package Manager Console,
  一旦这些命令被执行,相关的.sql文件就会被打开在Visual Studio